Re: NetServer::Generic -- welcome message ??
- From: anno4000@xxxxxxxxxxxxxxxxxxxxxxx (Anno Siegel)
- Date: 30 Mar 2006 12:54:27 GMT
Babacio <babacio@xxxxxxx> wrote in comp.lang.perl.misc:
More precisely, I would appreciate any suggestion of a simple
way to run a forked/preforked tcp server, that would behave
like the following one. (Any comment on the code is welcome
as well).
use IO::Socket;
my $server = IO::Socket::INET->new(LocalPort => 9101,
Type => SOCK_STREAM,
Reuse => 1,
Listen => 10 )
or die "$@\n";
while (my $client = $server->accept()) {
print $client "Welcome! Say 'quit' to leave.\n";
Why did you put this interaction outside the client loop?
while(1) {
my $x = <$client>;
last if $x =~ /^quit/i;
I'd put that last, so the "quit" interaction is logged as well.
$x =~ s/[\r|\n]//g;
print $client "You said $x!\n";
}
}
close($server);
To make a plain forked server, there isn't much to add. Just run
the client loop ("while ( 1 )...") in a forked process and exit after
the loop. Add a sigchld handler against zombies and error checking
and you're basically done. This is the loop (marginally tested)
$SIG{ CHLD} = 'IGNORE'; # good enough on most systems
while (my $client = $server->accept()) {
if ( my $pid = fork ) {
# parent does nothing here
} else {
print $client "Welcome! Say 'quit' to leave.\n";
die "can't fork" unless defined $pid;
while(1) {
my $x = <$client>;
$x =~ s/[\r|\n]//g;
print $client "(pid $$) You said $x!\n";
last if $x =~ /^quit/i;
}
exit;
}
}
If you need the ability for every client process to shut down the main
server, kill() the main process through an appropriate signal from the
child.
Anno
--
If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers.
.
- Prev by Date: Re: Arbitrarily Many Nested Loops
- Next by Date: FAQ 2.2 How can I get a binary version of perl?
- Previous by thread: Where to put Settings-Variables?
- Next by thread: Converting codepages to UTF8
- Index(es):
Relevant Pages
|
|