Reputation: 13406
I'm having a little trouble using sockets in a Perl server.
How can you know a (non-blocking) client just disconnected ? In C, I'm used to doing
if (recv(sock, buff, size, flags) == 0) {
printf("Client disconnected\n";
}
or the equivalent in python or other languages : recv
returns -1 if no data is available, 0 if client exited, a positive number if data could be read.
But perl's recv
doesn't work this way, and using $data = <$sock>
does not seem to give any possibility to know.
Is there any (simple) possibility ?
Upvotes: 4
Views: 2839
Reputation: 70812
You have to take a look at perldoc perlio
and perldoc IO::Socket
.
#!/usr/bin/perl -w
use IO::Socket;
There is a lot of ways to compose with non-blocking IOs, from PIPE
signal to recv
you could use (depending on what you are doing):
return "Socket is closed" unless $sock->connected;
That is how I've controlled many sockets to serve them with select
. When a socket is closed, I have to remove them from list (nothing else, as if disconnect, the socket doesn't exist anymore, so there is no need to close them):
unless (eval {$group{$grp}->{'socket'}->connected}) {
delete $group{$grp}->{'socket'};
return 0;
};
The eval
prevents a bad try to a disconnected socket which will end your script with a socket io error.
Hope this helps!
Upvotes: 1