4

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 ?

2
  • Are you using any asynchronous framework?
    – creaktive
    Dec 27, 2012 at 21:20
  • 2
    Note. When you say "recv returns -1 if no data is available". That's not entirely correct. recv will return -1 when there is no data available and set errno to either EAGAIN or EWOULDBLOCK. But there are other cases where recv could return -1 as well - mostly as a result of the TCP connection getting interrupted (e.g. remote peer crashed without shutting down his socket, losing internet, etc...). In other words, you shouldn't rely on "-1" being returned by recv. Always check the corresponding errno to see if it's a recoverable error.
    – selbie
    Dec 28, 2012 at 9:57

1 Answer 1

1

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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.