#!/usr/bin/perl # http://perlmonks.org/?node_id=1181364 use strict; use warnings; use IO::Socket; use IO::Select; my $listenport; my $othersocket; my $otherport; my $sendinterval; my $pc1 = @ARGV && $ARGV[0] eq 'pc1'; if( $pc1 ) { $listenport = 8010; $sendinterval = 5; $otherport = 'localhost:8000'; } else { $listenport = 8000; $sendinterval = 7; $otherport = 'localhost:8010'; } my $ls = IO::Socket::INET->new( Listen => 10, LocalPort => $listenport, Reuse => 1, ) or die "$@ opening listen socket on port $listenport"; warn "listening on $listenport\n"; my $sel = IO::Select->new($ls); my $nextsend = $sendinterval + time; while(1) { my $delta = $nextsend - time; if( $delta <= 0 ) { if( not defined $othersocket) { if( $othersocket = IO::Socket::INET->new($otherport) ) { warn "opened client at $otherport\n"; $sel->add( $othersocket ); } else { warn "open failed $@\n"; } } if( $othersocket ) { my $msg = $pc1 ? "ADD\n" : "STAT\n"; print $othersocket $msg; print "sent $msg"; } $nextsend = $sendinterval + time; } else { for my $h ($sel->can_read($delta)) { if($h == $ls) { $sel->add(my $new = $h->accept); } elsif(sysread $h, my $in, 1024) { if( $othersocket and $h == $othersocket ) { print "should be ack: $in"; } else { print "got $in"; print $h "ack to $in"; } } else { $othersocket and $h == $othersocket and $othersocket = undef; $sel->remove($h); close $h; print "closed.\n"; } } } } __END__