develooper Front page | perl.libwww | Postings from March 2002

HTTP echo server

Thread Next
From:
Sean M. Burke
Date:
March 2, 2002 15:11
Subject:
HTTP echo server
Message ID:
5.1.0.14.1.20020302160634.01e9dcb0@mail.spinn.net
I recently had reason to want to see exactly what request headers given
browsers would send, so I wrote this very rough HTTP server that simply
shows the client its own request. This is about my first attempt at
socket programming, so forgive me if I'm shocked that it works! (Even
under MSWin!)

  use strict;
  use IO::Socket qw(:DEFAULT :crlf);
  use constant MY_PORT => 9123;
  
  my $quit = 0;
  $SIG{'INT'} = sub {$quit = 1};
  
  my $socket = IO::Socket::INET->new(
    Listen => 20,
    LocalPort => MY_PORT,
    Timeout => 60 * 60,
    Reuse => 1,
  ) or die "Can't create listening socket: $!\n";
  print "Access me as http://localhost:", MY_PORT, "/\n";
  
  $/ = CRLF;
  my $session;
  while(!$quit) {
    next unless $session = $socket->accept;
    binmode($session);
    select($session);
    ++$|;
    select(STDOUT);
    
    my @gotten;
    do { push @gotten, scalar(<$session>) }
     while $gotten[-1] =~ m/\S/;
    print $session 'HTTP/1.0 200 OK', CRLF,
      # we really should send Server and Date too, but feh.
      'Content-type: text/plain', CRLF, CRLF,
      @gotten;
    close($session);
  }
  close($socket);
  exit 0;

__END__
--
Sean M. Burke    sburke@cpan.org    http://www.spinn.net/~sburke/


Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About