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}; } } }
In reply to Re: Developing an UDP chat server/client
by Aighearach
in thread Developing an UDP chat server/client
by Mandor
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |