|
0 #!/usr/bin/perl
1 # file: eliza_server.pl
2 use Chatbot::Eliza;
3 use IO::Socket;
4 use POSIX 'WNOHANG';
5 use constant PORT => 12000;
6 # signal handler for child die events
7 $SIG{CHLD} = sub { while ( waitpid(-1,WNOHANG)>0 ) { } };
8 my $listen_socket = IO::Socket::INET->new(LocalPort => PORT,
9 Listen => 20,
10 Proto => 'tcp',
11 Reuse => 1);
12 die "Can't create a listening socket: $@" unless $listen_socket;
13 warn "Server ready. Waiting for connections...\n";
14 while (my $connection = $listen_socket->accept) {
15 die "Can't fork: $!" unless defined (my $child = fork());
16 if ($child == 0) {
17 $listen_socket->close;
18 interact($connection);
19 exit 0;
20 }
21 } continue {
22 $connection->close;
23 }
24 sub interact {
25 my $sock = shift;
26 STDIN->fdopen($sock,"r") || die "Can't reopen STDIN: $!";
27 STDOUT->fdopen($sock,"w") || die "Can't reopen STDOUT: $!";
28 STDERR->fdopen($sock,"w") || die "Can't reopen STDERR: $!";
29 STDOUT->autoflush(1);
30 Chatbot::Eliza->new->command_interface;
31 }
|
|