How do you know that the socket client is disconnected?

I have a little problem using sockets on a Perl server.

How can you find out that the (non-blocking) client is simply 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 there is no data, 0 if the client is out, a positive number if the data can be read.

But perl recv doesn't work that way, and using $data = <$sock> doesn't seem to make it possible to know.

Is there a (simple) opportunity?

+4
source share
1 answer

You should take a look at perldoc perlio and perldoc IO::Socket .

 #!/usr/bin/perl -w use IO::Socket; 

There are many ways to build with non-blocking IOs, from the PIPE signal to recv , which you could use (depending on what you are doing):

 return "Socket is closed" unless $sock->connected; 

This is how I controlled a lot of sockets to serve them with select . When the socket is closed, I have to remove them from the list (nothing else, as if to disconnect, the socket no longer exists, so there is no need to close them):

 unless (eval {$group{$grp}->{'socket'}->connected}) { delete $group{$grp}->{'socket'}; return 0; }; 

eval prevents a bad attempt to disconnect a socket, which will terminate your script with an io socket error.

Hope this helps!

+1
source

All Articles