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>