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);
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.