Pre-sporked multithreaded socket communications. This will spawn off X number of threads to listen on a port. This will only work with a interpreter threads enabled with Perl (recent Activestate versions have this by default I believe). I'm actually using this code with a heavy hit server on a Solaris box.
use strict; use threads; use IO::Socket; # the port to listen on: my $PORT = 8989; # the number of threads to pre-spork: my $INITHREADS = 5; my $handle = IO::Socket::INET->new( LocalPort => $PORT, MultiHomed => 1, Type => SOCK_STREAM, Reuse => 1, Listen => 10) or die "Cannot open port $PORT: $!\n"; $handle->autoflush(1); for(1..$INITHREADS) { my $thr = threads->new(\&process)->detach(); } sleep(); # The parent thread sleeps forever. . . # You can potentially change this perma-sleep to # have the parent thread do dynamic thread management # but only if you don't detach() them. sub process { while(my $socklet = $handle->accept()) { # Here you can do your stuff # I use have the server talk to the client # via print $socklet and while(<$socklet>) # if you want to capture the IP address: # my $peerhost = $socklet->peerhost(); } }

Replies are listed 'Best First'.
Re: Pre-sporked multithreaded sockets
by Tommy (Chaplain) on Jan 21, 2003 at 00:25 UTC
    Thanks for this code snippet. It is very useful, and has been beneficial to me in developing perl programs that interact with a flash 5 front end. Good job.
    --
    Tommy Butler, a.k.a. TOMMY
    
      I'm glad you found it useful. Is the Flash part on the web where someone can check it out?
        Not yet, I'll let you know. It's only on my machine for now. Do you use flash?
        --
        Tommy Butler, a.k.a. TOMMY