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();
}
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.