Perl 简单的 Web 服务器不会同时处理多个请求



我写了一个简单的网络服务器,它应该连续处理并发请求。但是,即使在分离线程后,它也不会处理并发请求。有人可以帮忙吗?

Webserver.pl

use HTTP::Daemon;
use threads;
my $webServer;
my $package_map = {"test"  => "test"};
my $d = HTTP::Daemon->new(LocalAddr => $ARGV[0],
LocalPort => 80,
Listen => 20) || die;
print "Web Server started!n";
print "Server Address: ", $d->sockhost(), "n";
print "Server Port: ", $d->sockport(), "n";

while (my $c = $d->accept) {
threads->create(&process_req, $c)->detach();
}
sub process_req {
my $c = shift;
my $r = $c->get_request;
if ($r) {
if ($r->method eq "GET") {
my $path = $r->url->path();
my $service = $package_map->{$path};
if ($service) {
$response = $service->process_request($request);
}
}
}
$c->close;
undef($c);
}

test.pm

sub process_request
{
threads->create(&testing)->detach();
my $response = HTTP::Response -> new (200);
$response -> header('Access-Control-Allow-Origin', '*');
$response -> content("Success");
return $response; 
}
sub testing
{
my $command = 'echo "sleep 100" | ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 <dev_box>';
if (system($command) != 0) {
print "FAILEDn";
}
}

这是基于您的示例的代码,适用于我在 Windows 上。也许您可以向我们展示它如何/在哪里为您失败:

#!perl
use strict;
use warnings;
use HTTP::Daemon;
use threads;
my $webServer;
#my $package_map = {"test"  => "test"};
my $d = HTTP::Daemon->new(LocalAddr => $ARGV[0],
LocalPort => $ARGV[1] // 80,
Listen => 20) || die;
print "Web Server started!n";
print "Server Address: ", $d->sockhost(), "n";
print "Server Port: ", $d->sockport(), "n";

while (my $c = $d->accept) {
warn "New connection";
threads->create(&process_req, $c)->detach();
}
sub process_req {
my $c = shift;
while( my $r = $c->get_request ) {
if ($r) {
if ($r->method eq "GET") {
my $path = $r->url->path();
if (1) {
sleep 100;
$c->send_response( HTTP::Response->new(200, "OK", undef, "donen") );
}
}
}
};
$c->close;
}

相关内容

  • 没有找到相关文章

最新更新