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); }

In reply to Re: $Socket->connected Not Returning False? by pg
in thread $Socket->connected Not Returning False? by BronzeWing

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.