#!/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=8083, 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($fname =~ /\/help/)
        #{
        #  print "iam here \n";           
        #  print "hey iam looking at this $theFile\n";  
        #  $theFile = new IO::File "/$docRoot/tcs.html", "r";   
         
        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 "Transfer-Encoding: chunked \r\n";
          print FH "\r\n";
          print FH <$theFile>;                     # Print file to client
          undef $theFile;        
         }
       # } 
        else
        {
          print FH "HTTP/1.1 404 Not found\r\n";
          print FH "Date:$now\r\n";
          print FH "Server: myserver\r\n";
          print FH "Set-Cookie: JSESSIONID=abc; Path=/Saba\r\n";
          print FH "\r\n";
          print FH "<H1>$fname not found!</H1>";
        }
          close (FH);
    }
}
