Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: $Socket->connected Not Returning False?

by pg (Canon)
on Oct 21, 2003 at 04:29 UTC ( [id://300826]=note: print w/replies, xml ) Need Help??


in reply to $Socket->connected Not Returning False?

connected can not be used to check the actual state of the connection, instead it tells you whether the socket is locally closed.

What you can do is to use IO::Select, call can_read first, if can_read says yes, but when you read, you got undef back, then the connection is actually closed.

This solution resolves the confusion you mentioned, that you could not differentiate whether the socket is closed or just got an empty string on a open socket.

The following code demos this (tested under win98 with AS 5.8.0 build 802):

server.pl: use IO::Socket; use strict; my $server = new IO::Socket::INET(Timeout => 7200, Proto => "tcp", LocalPort => 3000, LocalHost => "localhost", Reuse => 1, Listen => 2); print "Server is listening for connection ...\n"; my $c = $server->accept; print "Connection accepted, now sleep 10 seconds ...\n"; sleep(10); close $c; print "Connection closed\n"; client.pl: use IO::Socket; use IO::Select; use strict; my $c = new IO::Socket::INET(Proto => "tcp", PeerAddr => "localhost", PeerPort => 3000, Timeout => 7200) || die "failed to connect to server\n"; print "Connected, $c\n"; my $sel = new IO::Select($c); while (1) { print "tick ...\n"; my @r = $sel->can_read(0); foreach (@r) { my $line = <$_>; print "$_ is closed\n" if (!defined($line)); } sleep(1); }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://300826]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (2)
As of 2024-04-19 01:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found