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

I have a simple client/server model setup with 2 scripts. The client connects to the server, sends some data, and then closes the connection. The server sits and receives the input over the socket. I want to have the server detect when the connection has been closed. I've been trying to use the connected function, but it is not working properly (prob. not using it correctly). I am using ActiveState for Windows.
Here is the code:
server:
use IO::Socket; use IO::Select; $read_set = new IO::Select(); # create handle set for reading $a = new IO::Socket::INET ( LocalHost => 'localhost', LocalPort => '80', Proto => 'tcp', Listen => 1, Reuse => 1, ); $read_set->add($a); $quit = 0; while ($quit == 0) { foreach $rh ($read_set->can_read(20)) { print "start\n"; my $new_sock = $rh->accept(); $temp = $new_sock->connected(); $temp2 = $rh->connected(); print "-$temp--$temp2-\n"; if ( not defined($new_sock->connected) ) { $quit = 1; last; } while(<$new_sock>) { print $_; } if ( not defined($new_sock->connected) ) { $quit = 1; print "not defined anymore\n"; } sleep 3; print "end\n"; $temp = $new_sock->connected(); $temp2 = $rh->connected(); print "-$temp--$temp2-\n"; } } close($sock);


client:
use IO::Socket; my $sock = new IO::Socket::INET ( PeerAddr => 'localhost', PeerPort => '80', Proto => 'tcp', Timeout => 10, ); die "Could not create socket: $!\n" unless $sock; while ($i < 5) { $i++; print $sock "sending the stuff $i\n"; print "sending the stuff $i\n"; sleep 2; } $sock->close(); sleep 20;

Is this even the right way to go about this?

Replies are listed 'Best First'.
Re: Socket connected function
by gam3 (Curate) on Apr 15, 2005 at 14:24 UTC
    You might try a port > 1024 and see if that works. On unix systems you need to be root to open a port < 1024. you also might want to test your new socket, such as:
    $a = new IO::Socket::INET ( LocalHost => 'localhost', LocalPort => '80', Proto => 'tcp', Listen => 1, Reuse => 1, ) or die "Could not open socket $!";
    -- gam3
    A picture is worth a thousand words, but takes 200K.
      Thanks, although it is able to open, send and receive without any problems.
Re: Socket connected function
by Tanktalus (Canon) on Apr 15, 2005 at 18:50 UTC

    My guess, from looking at my own usage of IO::Select, is to modify your while loop like this:

    while(<$new_sock>) { $quit = 1 unless length; print $_; }
    In other words, if reading from the socket got nothing, then it's done. (I use sysread reading from pipes, but shouldn't make a difference.)

    Also, inside your foreach loop, you shouldn't use $new_sock, you should use $rh. Makes your code more robust in case you add additional read-sockets into your IO::Select list.