#!/usr/bin/perl use strict; use warnings; use IO::Select qw( ); use IO::Socket::INET qw( ); my $sock = IO::Socket::INET->new( Proto => 'tcp', LocalPort => 1200, Listen => 5, Reuse => 1, ) or die "Socket couldn't be created: $!\n"; my %clients; # $clients{$rh}{state} = 'CONNECTED'; # $clients{$rh}{state} = 'UNCONNECTED'; # $clients{$rh}{rx_txt} = ''; my $select = new IO::Select(); $select->add($sock); sub handle_connection { my ($rh) = @_; # This function should spawn a thread to do its work because # 1) it could take a while if the file isn't small, and # 2) the write operation could block. my $client = $clients{$rh}; # Convenient alias. our $state; local *state = \($client{state}); open(my $fh, '<', '~/.somefile'); # Needs error handling here. while (<$fh>) { last if $state ne 'CONNECTED'; print $rh $_; } $state = 'UNCONNECTED'; $select->remove($rh); delete $clients{$rh}; print "UNCONNECTED (done)\n"; } while (1) { my @ready = $select->can_read(); foreach my $rh (@ready) { print "GOT SOMETHING!\n"; if ($rh == $sock) { my $conn = $sock->accept(); $select->add($conn); print "CONNECTION ADDED\n"; $clients{$conn} = { state => 'UNCONNECTED', rx_txt => '', }; next; } my $client = $clients{$rh}; # Convenient aliases. our $rx_txt; local *rx_txt = \($client{rx_txt}); our $state; local *state = \($client{state}); my $bytes_read = read($rh, $rx_txt, 1024, length($rx_txt)); if (!defined($bytes_read)) { # Socket error. $state = 'UNCONNECTED'; $select->remove($rh); delete $clients{$rh}; print "UNCONNECTED by socket error)\n"; next; } if (!bytes_read) { # Socket closed. $state = 'UNCONNECTED'; $select->remove($rh); delete $clients{$rh}; print "UNCONNECTED by client\n"; next; } my $cmd = $rx_txt =~ s/^(.*)\n// or next; if ($cmd ne 'HELLO') { $state = 'UNCONNECTED'; $select->remove($rh); delete $clients{$rh}; print "UNCONNECTED by invalid request\n"; next; } $state = 'CONNECTED'; print "CONNECTED\n"; handle_connection($rh); } }