#!/opt/threadperl/bin/perl -w # forking server use strict; use IO::Socket; #use the hash object in this module use riddle; # the riddle object my $cr = "\015"; my $lf = "\012"; # need this or the REAPER hack form perlipc on a forking server $SIG{CHLD} = sub { wait() }; my ($host, $port); die "Usage $0 host port" unless @ARGV == 2; $host =shift; $port =shift; my $sock = new IO::Socket::INET (Localhost=> $host, LocalPort=>$port, Proto=>'tcp', Listen=>5, Reuse=>1, ); die "Socket: $!" unless $sock; while ( my $client = $sock->accept() ) { my $pid = fork; if ( $pid ) { print STDERR "Parent pid $$ got new socket\n"; } else { print STDERR "Child pid $$ starting riddle protocol\n"; # create new object to handle protocol my $r = new riddle; #FIXME: should not start talking send_message( $client, $r->protocol("") ); while ( my $msg_in = fetch_message($client) ) { # protocol implemented in the riddle module my $msg_out = $r->protocol($msg_in); last unless $msg; send_message ($client, $msg); } close $client; print STDERR "Child pid $$ finished riddle protocol\n"; exit 0; } } # fetch message and do message integrity checks here sub fetch_message { my $sock = shift; my $msg = <$sock>; print STDERR "Child pid $$ got message $msg_in from client\n"; return $msg; } # send message and do error checks here sub send_message { my $sock = shift; my $mesg = shift; print $sock $mesg, $cr, $lf; } close $sock;