in reply to Event based handling of multiple connections with AnyEvent
Your question seems confused. Do you want to handle multiple connections in a single process, or do you want to write a forking or pre-forking server like Apache's httpd? All three are varying levels of easy.
Here's a single-process, event-driven way:
#!/usr/bin/env perl use warnings; use strict; # Note: POE's default event loop uses select(). # See CPAN for more efficient POE::Loop classes. use POE; use POE::Component::Server::TCP; POE::Component::Server::TCP->new( Port => 8888, ClientConnected => sub { print "Client connected.\n"; }, ClientInput => sub { my ($app, $storage, $input) = @_[KERNEL, HEAP, ARG0]; print "Got client input: $input\n"; $storage->{client}->put($input); $app->yield("shutdown") if $input eq "quit"; }, ClientDisconnected => sub { print "Client disconnected.\n"; }, ); POE::Kernel->run();
Here's another, adapted from Perl Cookbook recipe 17.11 (Forking Servers):
#!/usr/bin/env perl use warnings; use strict; use POSIX qw(:sys_wait_h); use IO::Socket::INET(); use IO::Handle; sub reaper { 1 until waitpid(-1, WNOHANG) == -1; $SIG{CHLD} = \&reaper; } $SIG{CHLD} = \&reaper; my $server = IO::Socket::INET->new( Listen => 5, ReuseAddr => 1, LocalPort => 8888, Proto => 'tcp' ); while (1) { my $client; my $client_addr = accept($client, $server); next unless $client_addr; # Fork to handle the connection. my $pid = fork(); # Parent should just accept again. next if $pid; # Handling errors is good. die "fork failed: $!" unless defined $pid; # Child here. close($server); $client->autoflush(1); print "$$: client connected\n"; while (<$client>) { chomp; print "$$: got input: $_\n"; print $client "$_\n"; last if /^\s*quit\s*/; } print "$$: client disconnected\n"; close $client; exit; }
Perl Cookbook recipe 17.12 (Pre-Forking Servers) is a couple pages long, so I'm not going to adapt it here. I believe the source is legally available online, and consider this incentive to buy a fine book.
|
|---|