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;
}
}
}
}
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|