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); #start 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 current 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 from outside $own_thread=threads->self(); $tid = threads->tid($own_thread); lock($tid); $session->autoflush(1); #make sure the socket get read right away while (1) {print "\n SEND( TYPE q or Q to Quit):"; my $recieved_data; my $send_data = ; STDIN->autoflush(1); chop($send_data); $session->send($send_data); $session->recv($recieved_data,1024);print "\n RECIEVED: $recieved_data";} }