if ($fh == $ircsock) {
...
if (sysread($ircsock, $ircdata, 512)) {
...
} else {
$sel->remove($ircsock);
close($ircsock);
...reopen $ircsock...
...add $ircsock to $sel...
}
As for the sysread issue, I'm talking not just about that regex but also the rest of them. For example when you have your /^JOIN\s*\#(\S+)/ regex. If the sysread returns something like JOIN #test\nJOIN #blah, your code will silently ignore the second command.
A slurpy read is one way to solve it, and for IRC this will probably work fine since the IRC protocol is linebased.
In general, it may be better to do something like:
my $clientdata = "";
while (1) {
#-- Add the new data at the end of the existing one
sysread $fh, $clientdata, 512, length $ircdata;
#-- See if we have a full line we can process
while ($fh =~ s/^(.*?)\r?\n//) {
my $line = $1;
... do your per-line regex stuff here...
}
}
This means of course that in your case you need to keep track of $clientdata on a per-filehandle basis (have something like an %clientdata hash keyed on the filehandle). And of course you wouldn't have the while (1) in your code.
Update: A few more ways in which your current sysread code can go wrong: if the server sends a >512 byte line, you will send this to your clients as two lines with a newline inbetween, because you unconditionally add a \n after your print to the clients. In this particular case you're probably better off just removing the chomp($ircdata) and print the string to the clients as-is.
Your current code also silently drops server messages to clients that can't currently receive them. This may be what you intended of course.
One last issue I forgot is your use of \n to terminate lines you send to the server (i.e. in your NAMES or TOPIC commands). The IRC protocol specifies that all lines need to be termiated with \015\012. If you're running your code on windows you're in luck since that's exactly what \n generates, but on other platforms this may not be the case so it's safer to explicitely use \015\012 (or some suitable constant of course). |