To get the code to work reliably on Windows7 (ActiveState Perl v5.12.4) I had to add a sleep of at least 15ms after the thread creation. I use 50ms for good measure:
use Time::HiRes qw( usleep );
...
while (my $c = $d->accept) {
threads->create(\&process_one_req, $c)->detach();
usleep(50_000);
}
Update: after attempting AJAX POSTs with some jQuery/JavaScript, the Perl web server code was not reliable. I seemed to loose AJAX messages. (As a workaround, I installed an AJAX error handler in the JavaScript code, which performs the same AJAX POST again (well, using setTimeout)... that worked, since I can tolerate multi-second delays -- the app updates graphs that are generated only every 4 seconds.)
Update: after playing around with this some more, I was able to get reliable operation, and handle multiple browsers and multiple requests per connection/browser if I closed the client connection/socket in the server, and the daemon/server socket in the client:
use HTTP::Daemon;
use threads;
my $d = HTTP::Daemon->new(LocalAddr => $ARGV[0],
LocalPort => 80,
Reuse => 1,
Listen => 20) || die;
print "Web Server started, server address: ", $d->sockhost(), ", serve
+r port: ", $d->sockport(), "\n";
while (my $c = $d->accept) {
threads->create(\&process_client_requests, $c)->detach;
$c->close; # close client socket in server
}
sub process_client_requests {
my $c = shift;
$c->daemon->close; # close server socket in client
while(my $r = $c->get_request) {
if ($r->method eq "GET") {
my $path = $r->url->path();
$c->send_file_response($path) or die $!;
#or do whatever you want here
} else { print "unknown method ".$r->method."\n" }
}
$c->close;
}
|