in reply to Re^2: Can a socket listen for multiple hosts? -- UPDATE
in thread Can a socket listen for multiple hosts?
Don't use buffered IO (e.g. read, readline aka <>) with select. You could get into a situation where data is waiting in Perl's buffer, and select wouldn't know anything about it.
Don't use IO that blocks after it reads all that's available to be read (e.g. read, readline aka <>) with select. It defies the purpose of using select.
You don't handle EOF, so you could end up having a handle that's permanently ready to read.
Fixed:
#!/usr/bin/perl use strict; use warnings; use IO::Socket::INET qw( ); use IO::Select qw( ); sub process_msg { my ($client, $msg) = @_; chomp $msg; my $host = $client->peerhost; print "$host said '$msg'\n"; return lc($msg) eq 'quit; } my $server = IO::Socket::INET->new( ... ) or die("Couldn't create server socket: $!\n"); my $select = IO::Select->new($server); my %bufs; while (my @ready = $select->can_read) { for my $fh (@ready) { if ($fh == $server) { my $client = $server->accept; $select->add($client); $bufs{fileno($client)} = ''; my $host = $client->peerhost; print "[Accepted connection from $host]\n"; } else { our $buf; local *buf = \$bufs{fileno($fh)}; my $rv = sysread($fh, $buf, 64*1024, length($buf)); if (!$rv) { my $host = $fh->peerhost; if (defined($rv)) { print "[Connection from $host terminated]\n"; } else { print "[Error reading from host $host: $!]\n"; } process_msg($fh, $buf) if length($buf); delete $bufs{fileno($fh)}; $sel->remove($fh); next; } while ($buf =~ s/\G(.*\n)//g) { if (!process_msg($fh, "$1")) { my $host = $fh->peerhost; print "[Connection from $host terminated]\n"; delete $bufs{fileno($fh)}; $sel->remove($fh); last; } } } } }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^4: Can a socket listen for multiple hosts? -- UPDATE
by sierpinski (Chaplain) on Jan 27, 2010 at 17:57 UTC | |
by ikegami (Patriarch) on Jan 27, 2010 at 19:06 UTC | |
Re^4: Can a socket listen for multiple hosts?
by sierpinski (Chaplain) on Feb 01, 2010 at 13:36 UTC | |
by ikegami (Patriarch) on Feb 01, 2010 at 15:13 UTC | |
by sierpinski (Chaplain) on Aug 16, 2010 at 15:16 UTC |
In Section
Seekers of Perl Wisdom