#  SocketDaemon2.pl
#  Example: 7.24
#  ----------------------------------------
#  From "Win32 Perl Scripting: Administrators Handbook" by Dave Roth
#  Published by New Riders Publishing.
#  ISBN # 1-57870-215-1
#
#  This script uses Perl v5.6's fork() function to implement a more efficient
#  version of Example_11_22.pl.

# Forking for Win32 starts with version 5.006
require 5.006;
use IO::Socket;

$iProcessCount = 0;
$Port = 8080;
                
if( $Socket = IO::Socket::INET->new( LocalPort => $Port, Listen => 5 ) )
{
    while( 1 )
    {
        print "\nListening for a connection...\n";
        last unless ( $Connection = $Socket->accept() );
        $iProcessCount++;
        print STDERR "Server: Connection $iProcessCount\n";

        MyFork( $Connection );
        $Connection->close();
    }
}

sub ProcessAsChild
{
    my( $Socket ) = @_;

    $Socket->send( "Child process $iProcessCount has started at " . localtime() . "\n" );
    while(1)
    {
        $Socket->recv( $In, 100 );
        last if( $In eq "\n" || $In eq "" );
        $Socket->send( "You entered: $In" );
    }
    print "\tChild $iProcessCount is closing.\n";
    $Socket->close();
}

sub MyFork
{
    my( $Socket ) = @_;
    my $Pid = fork();

    if( 0 == $Pid )
    {
        # We get here only if we are a child process
        $| = 1;
        ProcessAsChild( $Socket );
        exit();
    }
}

