#!/opt/threadperl/bin/perl -w # threaded server use utf8; use IO::Socket; use Thread; # use the phash object here use riddle1; use strict; our $cr = "\015"; our $lf = "\012"; my ($host, $port); die "Usage $0 host port" unless @ARGV == 2; $host = shift; $port = shift; our $sock = new IO::Socket::INET (Localhost=>$host, LocalPort=>$port, Proto=>'tcp', Listen=>5, Reuse=>1, ); die "Socket: $!" unless $sock; while ( my $new = $sock->accept() ) { # create object to handle protocol my $riddle = new riddle; # create thread to handle connection my $thr = new Thread \&runThread, $new, $riddle; # run the thread and forget about it $thr->detach(); print STDERR "Starting protocol for server $$, thread " . $thr->tid() . "\n"; } # cleanup on exit close $sock; sub runThread { # this part does the same thing as the child of # a forking server print STDERR "Thread " . Thread->self->tid() . " starting\n"; my $client = shift || die "Bad socket"; my $riddle = shift || die "No riddle object"; # should not start talking my $msg = $riddle->protocol("") || die "Protocol error"; send_message($client, $msg); while ( my $line = fetch_message($client) ) { my $msg = $riddle->protocol($line); last unless $msg; send_message($client, $msg); } close $client; print STDERR "Thread " . Thread->self->tid() . " done\n"; } # fetch message and do message integrity checks here sub fetch_message { my $sock = shift; my $msg = <$sock>; print STDERR "Got a line $msg 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; }