hi all, I am trying to write a simple perl http server to polish my perl skills.
Below is my code, the first time I access to localhost:8090, it can display the page. However, when I refresh the page, nothing produces in the browser, what is the problem of my code?
Thanks
use feature ':5.10'; use IO::Socket; use Carp; #use URI::Escape; use Readonly; $|++; Readonly::Scalar my $port => '8090'; my $socket = IO::Socket::INET->new( Listen => 5, LocalAddr => 'localhost', LocalPort => $port, Reuse => 1, Proto => 'tcp', ) or croak "Can not bind port: $!"; my $quit = 0; print "Server started at $port\n"; while (!$quit) { local $SIG{PIPE} = 'IGNORE'; while (my $session = $socket->accept) { my $chunk = ''; my $n = 0; my @headers; my ($method, $uri, $protocol); while (sysread($session, my $buffer, 1)) { last if $buffer eq "\n"; $chunk .= $buffer; } $_ = $chunk; m/^(\w+)\s+(\S+)(?:\s+(\S+))?\r?$/; $method = $1 || ''; $uri = $2 || ''; $protocol = $3 || ''; my $bad_request_doc = join "", <DATA>; return unless $method =~ /^(?:POST|GET|DELETE|PUT|HEAD)$/; $chunk = ''; while (sysread($session, my $buffer, 1)) { if ($buffer eq "\n") { $chunk =~ s/[\r\l\n\s]+$//; if ($chunk =~ /^([^()<>\@,;:\\"\/\[\]?={} \t]+):\s*(.* +)/i) { push @headers, $1 => $2; } last if ($chunk =~ /^$/); $chunk = ''; } else { $chunk .= $buffer; } } print $session "HTTP/1.0 200 OK\r\n"; print $session "Content-Type: text/html\r\nContent-Length: ", length($bad_request_doc), "\r\n\r\n", $bad_request_doc,"\n"; close $session; } } __DATA__ <html> <head> <title>Bad Request</title> </head> <body> <h1>Bad Request</h1> <p>Your browser sent a request which this web server could not grok.</p> </body> </html>

In reply to Http server problem by woosley

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.