sky50 has asked for the wisdom of the Perl Monks concerning the following question:

Hello all, this is my first post here, so I hope I don't screw it up :) I've been looking at the Question/Answer stuff on sockets, and I'm haven't found anything addressing my problem. Basically, I'm trying to send a string over a socket, and not necessarily to a webserver, but I'll use that in my example, and check the return value for a certain string. I can do the check no problem, its actually getting the stuff to check that has been a problem. I use IO::Socket to set up all the socket stuff. I can 1) send the string over the socket, and 2) output the return stuff. However, after all the stuff returns, it just leaves me hanging . . .the rest of the code doesn't execute. From the commmand line (linux), if I do a 'telnet www.espn.com 80' and then 'GET /index.html HTTP/1.0', it'll return the html stuff, then exit out. However, I think whats happening in my program is that the remote host is closing its connection, but my side is staying open, still waiting for more input. Considering I'll be looking at various things like webservers, email servers, etc. I can't set a had value, like look at 10 lines, then exit. I'm not sure how to check if their connection has been closed. Sorry I'm being so wordy, but thanks ahead of time.
use IO::Socket $ip = "204.202.136.31"; ## www.espn.com for fun :) $port = "80"; $socket = IO::Socket::INET->new(PeerAddr => $ip, PeerPort => $port, Proto => "tcp", Type => SOCK_STREAM) or die "@"; print $socket "GET /index.html HTTP/1.0\n\r\n\r"; while (<$socket>) { print $_; } close ($socket);

Replies are listed 'Best First'.
Re: IO::Socket leaves me hanging
by bikeNomad (Priest) on Jun 20, 2001 at 07:50 UTC
    Look at the subroutine 'request' in LWP::Protocol::http for details as to how to handle sockets. Here's a little test program you can debug to watch (from the LWP::UserAgent manpage):
    # Create a user agent object use LWP::UserAgent; $ua = new LWP::UserAgent; $ua->agent("AgentName/0.1 " . $ua->agent); # Create a request my $req = new HTTP::Request GET => 'http://www.espn.com'; # Pass request to the user agent and get a response back my $res = $ua->request($req); # Check the outcome of the response if ($res->is_success) { print $res->content; } else { print "Bad luck this time\n"; }
    Basically, they're using IO::Select to wait for data to become available, with a timeout.:
    die "read timeout" if $timeout && !$sel->can_read($timeout); $n = $socket->sysread($buf, $size, length($buf));
    where $sel is an IO::Select object.
(tye)Re: IO::Socket leaves me hanging
by tye (Sage) on Jun 20, 2001 at 17:41 UTC

    After fixing the typos, your script works for me (and doesn't hang at the end). Just a data point.

            - tye (but my friends call me "Tye")