in reply to Using socket descriptor with IO::Select

Ok, the following is taken from a simple perl irc server that I was using as a basis for writing something else. Is this what you were talking about? This is very simple, and just prints everything that it gets out. It's simpler than it looks, I promise. Just look it over.

#!/usr/bin/perl

use strict;

use IO::Socket;
use IO::Select;
use POSIX;

my $server;
my $select;
my %clients;

$SIG{INT} = sub { foreach(values(%clients)) { close; } close $server; exit; };

sub start_listening {
  $server = IO::Socket::INET->new(Proto=>"tcp", LocalPort=>"8900", Listen=>1) or
 die "Can't open socket\n";
  $select = IO::Select->new($server);
}

sub main_loop {
  while(1) {
    foreach my $client ($select->can_read(1)) {
      if($client == $server) { #connection waiting to be handled...
        $client = $server->accept();
        $select->add($client);
        &setnonblocking($client);
        $clients{$client} = $client;
      } elsif(defined($clients{$client})) {
        my $pending;
        my $data;
        
        $pending = $client->recv($data,POSIX::BUFSIZ,0);
        
        if($pending) {
          print $data;
        }
      }
    }
  }
}

sub setnonblocking {
  my $sock = shift;
  # Get the current state of the socket..
  my $flags = fcntl($sock, F_GETFL, 0) or
    die "Can't get the flags on socket: $!\n";
  # ..and then add O_NONBLOCK (nonblocking-ness) on to it.
  fcntl($sock, F_SETFL, $flags | O_NONBLOCK) or
    die "Can't set socket non-blocking: $!\n";
}   

start_listening();
main_loop();
  • Comment on RE: Using socket descriptor with IO::Select