# /usr/bin/perl -Imodules
# file: web_serial.pl
# Figure 14.2: The baseline server handles requests serially

use IO::Socket;
use Web;

my $port = shift || 80;
my $socket = IO::Socket::INET->new( LocalPort => $port,
				    Listen    => SOMAXCONN,
				    Reuse     => 1 ) or die "Can't create listen socket: $!";

my $pid;

print "#####################################\n";
print "-= # WebServer started on Port 80 #=-\n";
print "#####################################\n";

#while (my $c = $socket->accept) {
#  
#  handle_connection($c);
#  close $c;
#};
#close $socket;

while (my $c = $socket->accept) {
	
	$socket->autoflush(0);
	$ClientSocket_ip = getpeername($c);
	($port, $ipaddr) = unpack_sockaddr_in($ClientSocket_ip);
	$ClientSocket_ip = inet_ntoa($ipaddr);

	if ($pid = fork) {
		close $socket;
	} elsif (defined $pid) {
		print "\t -=# Serving '$ClientSocket_ip' #=- \n";
		handle_connection($c);
		close $c;
		undef $pid;
	} else {
		die "fork error: $!";
	};
};
