#!/usr/bin/perl
use Socket; 
use IO::File; 
use POSIX qw(:sys_wait_h);
$docRoot = "/var/www/html/httpserver";
$proto = getprotobyname('tcp');
socket(F, PF_INET, SOCK_STREAM, $proto);           # TCP socket
$sin = sockaddr_in($port=8081, INADDR_ANY);                # Use random port
print "Imoprtant please use this $port port number in client to access the server \n";
bind(F, $sin);                                     # Bind F to port 80
listen(F,1);                                       # Listen for 1 connection 

while(accept(FH, F))                               # Wait for client connections
{
   select(FH);   $|=1;                             # Don't buffer I/O
   select(STDOUT);                                 # Set default print 

    if($process_id=fork)				#if process id is non zero execute child i.e client
    {
     $line = <FH>;                                 # Read first client line
     $line1 = <FH>;                                # Read first client line
     ($get, $line) = split(/GET /, $line);         # Locate GET
     ($fname, $line) = split(/ /, $line);          # File name
     print "Looking at $docRoot/$fname \n";
     $expression = "$docRoot/$fname";
     $theFile = new IO::File "$docRoot/$fname", "r"; # Open, assume on same drive as server
     $now=localtime();


         
        if (defined $theFile)
        { 
          print FH "HTTP/1.1 200 OK\r\n";
          print FH "Date:$now\r\n"; 
          print FH "Server: myserver\r\n";
          print FH "Accept-Ranges: bytes\r\n";
          print FH "Connection: Keep-Alive \r\n"; 
          print FH "Content-Type: text/html \r\n";
    #      print FH "Cache-control: no-cache, must-revalidate \r\n";
          print FH "last-modified: Mon, 24 Feb 2004 18:30:00 GMT \r\n";
          print FH "Junk: noe \r\n";
         print FH "Vary: Accept-encoding \r\n";
     #    print FH "Set-Cookie: c1=v1 \r\n";
#          print FH "Transfer-Encoding: chunked \r\n";
          print FH "\r\n";
          print FH <$theFile>;                     # Print file to client
          undef $theFile;        
         }
        else
        {
          print FH "HTTP/1.1 100 Continue\r\n";
          print FH "Date:$now\r\n";
          print FH "Server: myserver\r\n";
          print FH "\r\n";
          print FH "<H1>$fname not found!</H1>";
        }
          close (FH);
    }
}
