in reply to TCP server, that realizes connection loss

You might want to use Select (if possible on win32? ) See Knowing when a socket connection is dead and $Socket->connected Not Returning False? for instance.

Also read perldoc IO::Socket and look for the "connected" method.

  • Comment on Re: TCP server, that realizes connection loss

Replies are listed 'Best First'.
Re^2: TCP server, that realizes connection loss
by sven (Initiate) on Jul 15, 2009 at 12:44 UTC
    Hi,

    select kinda does the trick. I can now monitor the server. If the client disconnects, it is captured and the thread running the read/write is killed.

    now I have another problem. Even though a new socket seems to be opened after reconnect, I can only write to it, when I have the print"$pid \n"; before cancelling the thread. If i comment that out, it just prints out:

    SEND( TYPE q or Q to Quit): RECIEVED: SEND( TYPE q or Q to Quit): RECIEVED: SEND( TYPE q or Q to Quit):Use of uninitialized value $send_data in sc +alar chop at select_server.pl line 46, <STDIN> line 5. RECIEVED: SEND( TYPE q or Q to Quit):Terminating on signal SIGINT(2)

    The error above shows up when hitting CTRL-C

    What am I missing?
    use IO::Select; use IO::Socket(); use threads; use threads::shared; use Thread::Cancel ; use strict; use warnings; my $Thread; my $lsn = new IO::Socket::INET(Listen => 1, LocalPort => 5000); my $sel = new IO::Select( $lsn ); my $tid : shared; while(my @ready = $sel->can_read) { foreach my $fh (@ready) { if($fh == $lsn) { # Create a new socket my $new = $lsn->accept; $sel->add($new); my $Thread = threads->create( "echoserver", $new); #s +tart the echo-server as a seperate thread #$Thread->detach(); } else { # Process socket # Maybe we have finished with the socket print "$tid\n"; my $Thread = threads->object($tid); #get handle of cu +rrent echo-server thread $sel->remove($fh); $fh->close; threads->cancel($Thread); #kill the thread. + a new one will get started when we reconnect } } } sub echoserver { #Clienthandle my $session = shift; my $own_thread; # get our own thread-id and store it, so we can kill the thread fr +om outside $own_thread=threads->self(); $tid = threads->tid($own_thread); lock($tid); $session->autoflush(1); #make sure the socket get read right aw +ay while (1) {print "\n SEND( TYPE q or Q to Quit):"; my $recieved_data; my $send_data = <STDIN>; STDIN->autoflush(1); chop($send_data); $session->send($send_data); $session->recv($recieved_data,1024);print "\n RECIEVED: $recie +ved_data";} }

    Thanks,

    Sven