Whenever I use concurrent clients to connect to a self-rolled server, I encounter strange "blocking" issues. Why?
test-server.pl:
##!/usr/bin/perl
use HTTP::Daemon;
use Data::Dumper;
my $d = HTTP::Daemon->new(
LocalAddr => 'localhost',
LocalPort => 4242,
ReuseAddr => 1
) || die;
my $cnt;
# response loop
while (my $c = $d->accept) {
while (my $request = $c->get_request) {
print "Request:\n".Dumper($request);
my $response = HTTP::Response->new( 200, 'OK');
$response->header('Content-Type' => 'text/html'),
$response->content("$cnt Working!");
$cnt++;
# print "Response:\n".Dumper($response);
$c->send_response($response);
}
$c->close;
undef($c);
}
test-client.pl:
#perl
use LWP::UserAgent;
use HTTP::Request;
my $ua = LWP::UserAgent->new;
for(1..10000){
## build request
print "$_ GET:\n";
$req = HTTP::Request->new('GET' => 'http://localhost:4242/');
## Pass request to the user agent and get a response back
my $res = $ua->request($req);
if ($res->is_success) {
print $res->status_line ."\n". $res->headers->as_string . $r
+es->content;
}else{
print $res->status_line, "\n";
}
print "\n\n";
sleep(1);
}
Start the server and then use your browser to connect to
http://localhost:4242. Hit reload a couple of times. It will work. Then fire the test-client.pl script and it will hang on request number one.
Stop the server. Then try it the other way round: First start the server again. Then fire the test-client.pl and this time it will count up requests. Now, as soon as you use your browser to connect to
http://localhost:4242 the test-client will stop getting requests through, while the browser does, doing reloads again and again, as if it could grab the socket from the test-client. (Even better: as soon as you close the browser(!), not just the tab, the CLI test-client resumes counting up successful requests.)
Although this is a non-forking server, it should process one request after another. Right? But it seems as if it serves only one connection/one client on a first come first serve basis. Blocking all other requests...
I've never got my head completely around Socket programming, and in the past I ran into the strangest blocking issues. This here somehow seems related.
I've seen the same behavior with Net::Server, POE and Anyevent based server scripts, so it seems to be related to what I am doing with these modules... What am I missing??