Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I want to implement my own simple webserver to share data from one of my machines to pass information from one of my machines to the other.

I'm trying to use IO::Socket but seem to be running into trouble. I want to read the request and headers and then print out the appropriate page

use strict; use IO::Socket; my $server = IO::Socket::INET->new ( Proto => "tcp", LocalPort => 3000, Reuse=>1, Listen=>10 ) or die "Cannot connect to time service"; my ($request,$remote); $server->autoflush (1); while (defined($remote=$server->accept())) { $remote->autoflush(1); $request=<$remote>; print $request."\n"; }
I try connecting with my web browser to the machine on the correct port but the server never seems to take any of the action within the while loop.

Any help would be most appreciated.

Replies are listed 'Best First'.
Re: How do I write a simple webserver
by lhoward (Vicar) on Sep 18, 2000 at 06:26 UTC
    How about starting a layer higher and building your webserver ontop of the HTTP::Daemon module?
    use HTTP::Daemon; use HTTP::Status; $d = new HTTP::Daemon; print "Please contact me at: <URL:", $d->url, ">\n"; while ($c = $d->accept) { $r = $c->get_request; if ($r) { if ($r->method eq 'GET' and $r->url->path eq "/xyzzy") { # this is *not* recommened practice $c->send_file_response("/etc/passwd"); } else { $c->send_error(RC_FORBIDDEN) } } $c = undef; # close connection }
Re: How do I write a simple webserver
by merlyn (Sage) on Sep 18, 2000 at 06:24 UTC
RE: How do I write a simple webserver
by Zarathustra (Beadle) on Sep 18, 2000 at 09:02 UTC

    Here's something super cheezy I just wrote up as a quick excersize for myself. It does what you ask for...

    use strict; use IO::Socket; my $server = IO::Socket::INET->new ( Proto => "tcp", LocalPort => 3000, Reuse=>1, Listen=>10 ); my ( $pid, $host, $date ); $date = scalar localtime(); sub spawn_srvr { my ( $vers, $page, %hdrs ); while (<$host>) { /^(GET)\s(.*)/ && do { $hdrs{$1} = $2; next; }; /^((\w|-)+):(.*)/ && do { $hdrs{$1} = $3; next; }; /\n/ and do { ( $page, $vers ) = split(/\s/, $hdrs{'GET'}, 2); if ( open(FH, "<$page") ) { print $host <<EOF; HTTP/1.1 200 OK Date: $date Server: LameWeb Connection: close Content-Type: text/html EOF print $host $_ while ( <FH> ); } else { print $host <<EOF; HTTP/1.1 404 Not Found Date: $date Server: LameWeb Connection: close Content-Type: text/html <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> <HTML><HEAD> <TITLE>404 Not Found</TITLE> </HEAD><BODY> <H1>Not Found</H1> The requested URL $page was not found on this server.<P> </BODY></HTML> EOF } last; }; } kill(9, $pid) && print "killed pid: $pid\n"; } while () { $host = $server->accept(); if ($pid = fork()) { spawn_srvr(); } $host->close; }

      To tell the browser that you are done, you need to close the socket: close $host

              - tye (but my friends call me "Tye")