use strict; use IO::Socket::INET; use IO::Select; my $sock = IO::Socket::INET->new(LocalPort => 4455, Listen => 5); my $select = IO::Select->new($sock); my %gremlins; # list of gremlins! for(;;) { #mainloop if(my @socks = $select->can_read(0)) { #non-blocking check for data for my $gremlin (@socks) { if($gremlin eq $sock) { # connection my $c = $sock->accept(); next unless $c; my $init = <$c>; chomp $init; $gremlins{$c} = [$c,$init]; # can't store actual ref as key print "Added gremlin $init\n"; $select->add($c); # add to list of sockets } else { if($gremlin->eof()) { #child died! print "Gremlin $gremlins{$gremlin}[1] died\n"; $select->remove($gremlin); delete $gremlins{$gremlin}; next; } #message for you, sire! my $msg = <$gremlin>; chomp $msg; print "Got message '$msg', sending to gremlins\n"; for(keys %gremlins) { next if $_ eq $gremlin; #dont send the message to sender my $c = $gremlins{$_}[0]; #sock of peer print $c "$gremlins{$_}[1]: $msg\n"; #send to other gremlins everything we get, as an exercise } } } } sleep 1; } #### use strict; use IO::Socket::INET; use IO::Select; my $sock = IO::Socket::INET->new(PeerAddr => "localhost:4455"); print $sock "Pid $$\n"; # the init string, used as a 'name' for this client, you may want something more descriptive/informative etc. my $select = IO::Select->new($sock); my $i = 0; for(;;) { #main loop unless(int(rand(5))) { my $msg = "It has been $i iterations since I last sent something\n"; print "Sending message: $msg"; print $sock $msg; $i=0; } if($select->can_read(0)) { #could capture sockets, but there is only one die "observer gone\n" if $sock->eof(); print "Got a message:\n ".<$sock>; } $i++; sleep 1; }