Perl Web Server

A simple http server written in Perl, it will serve up the webpage on port number 8080.

At the moment, it doesn’t have any error handling.

To test
1) Execute from the Shell
2) Create a HTML page. eg. index.html
3) Fire up a web browser and surf up to http://127.0.0.1:8080/index.html

#!/usr/bin/perl -w

usestrict;

useIO::Socket;

$SIG{CHLD} = sub { wait };

#http://docstore.mik.ua/orelly/perl/prog/ch03_189.htm

my %mime_type = (

    “gif”=>“image/gif”,  

    “jpg”=>“image/jpeg”, 

    “jpeg”=>“image/jpeg”,

    “png”=>“image/png”,  

    “htm”=>“text/html”,  

    “html”=>“text/html”, 

    “css”=>  “text/css”,

    “js”=>“text/javascript”);

my $server = IO::Socket::INET->new(LocalPort => 8080,

                    Type => SOCK_STREAM,

                       Reuse => 1,

                      Listen => 10) or die $!\n;

my $client ;

while ( $client = $server->accept())

{

    next if my $pid = fork;

    die“fork – $!\nunlessdefined $pid;

     my $client_info;

     while(<$client>)

     {

         last if/^\r\n$/;

         $client_info .= $_;

     }

    #print $client_info;

    

    $client_info =~/^GET \/(.*?)\.(\w*)\s/;

    print“filename is $1 extension is $2\n;

    

    my $filename = $1.“.”.$2;

    my $extension = lc($2); 

    my $selected_mime = defined ($mime_type{$extension}) ? $mime_type{$extension}: “text/plain”;

    print $client “HTTP/1.0200 OK\r\n;

    print $client “Content-type: “.$selected_mime .\r\n\r\n;

    open (INFILE, ‘<‘, $filename) || die “Problems: $!;

    while(<INFILE>)

         {

        print $client “$_”;

    }

    #print $client $client_info;

    close($client);

    exit( $pid );

}

continue

{

    close($client); 

    kill“CHLD”,$$;

}

 

  1. You’re in reality a good webmaster. The website loading pace is incredible. It seems that you are doing any unique trick. Also, The contents are masterpiece. you have performed a excellent activity on this topic!

Leave A Comment?