I don't have an answer to the main part of your question, as I haven't used UDP, but I have an answer for something fundamental that might be missed.
You don't need to fork or thread to use TCP efficiently. It is sometimes a good way to do it, but here is an example of another way. If you like it, read the manual pages for the packages useed. Notice in particular IO::Select.
use IO::Socket;
use IO::Select;
use Tie::RefHash; #there are also lots of slower ways to keep track of
+ the connections ;)
use POSIX; #for usefull constants
my %connections;
my $port = 5000;
tie %connections, qw( Tie::RefHash ); # so we can use refs as hash key
+s
my $server = IO::Socket::INET->new(
Listen => SOMAXCONN,
LocalPort => $port,
Reuse => 1,
Proto => 'tcp',
)
or die "can't open connection: $!";
$server->blocking( 0 );
my $select = IO::Select->new( $server );
while('eternity'){
foreach my $connection ( $select->can_read(60) ) {
if ( $connection == $server ) {
# new connection waiting
my $client = $connection->accept;
$client->blocking( 0 );
$select->add( $client );
$connections{$client} = time; # I like to know how long a user
+ has been connected, you could also set this to anything; we're just
+using the key for fast lookup.
}
elsif ( exists $connections{$connection} ) {
# user sending us data
my $length = $connection->sysread(my $data,POSIX::BUFSIZ);
if (defined $length && length $data) {
print "got '$data' from ",$connection->peerhost,':',$conne
+ction->peerport,"\n";
}
else {
# No data, probably EOF or an error, so close
$select->remove( $connection );
delete $connections{$connection};
}
}
}
-- Snazzy tagline here
|