【发布时间】:2013-06-19 22:35:13
【问题描述】:
我在 Windows (ActivePerl 5.10.1 build 1006) 下使用 Perl 创建了一个服务器,该服务器在连接时分叉,接受一些 JSON 数据,并将其写入数据库。我在 64 个客户端连接到服务器后遇到问题,尝试分叉时出现“资源不可用”的错误消息。
在 Linux 下运行此代码,我发现许多已失效的子进程,通过在父进程上添加 wait() 调用解决了这个问题。然而这并没有解决问题。在 Linux 下运行代码可以超过 Windows 中允许的 64 次调用。
我还启动了一个虚拟 Windows 服务器,以防服务器受到限制,但全新安装的 Perl 导致相同的 64 个连接限制。
感谢任何想法。
use IO::Socket;
use Net::hostent;
use JSON;
use DBI;
use Data::Dumper;
my $port=shift || 9000;
my $clients_served = 0;
while(1){
my $server = IO::Socket::INET->new( Proto => 'tcp',
LocalPort => $port,
Listen => 1,
Reuse => 1);
die "can't setup server" unless $server;
print "[Server $0 is running]\n";
####
# wait for a client to connect
# once it has, fork to a seperate thread and
# retrieve the JSON data
####
while (my $client = $server->accept()) {
my $pid = fork();
if ($pid != 0) {
print ("Serving client " . $clients_served++ . "\n");
}else{
$client->autoflush(1);
my $JSONObject = JSON->new->ascii->pretty->allow_nonref();
my $hostinfo = gethostbyaddr($client->peeraddr);
my $client_hostname = ($hostinfo->name || $client->peerhost);
printf "connect from %s\n", $client_hostname;
print " $client_hostname connected..\n";
syswrite($client, "Reached Server\n", 2048);
if (sysread($client, my $buffer, 2048) > 0) {
foreach my $tasks($JSONObject->decode($buffer)){
foreach my $task (@$tasks){
insert_record($client_hostname, $task); #empty method, contents does not affect result
}
}
}
print " $client_hostname disconnected..\n";
close $client;
exit 0;
}
}
$server->close();
}
exit 0;
【问题讨论】:
-
64 个套接字对任何人来说都应该足够了——比尔·盖茨
-
哪个 Windows 版本?非服务器版本对传入连接数有各种限制。
-
我仍然惊讶于 Windows 如何教会人们重新安装是首先要做的事情之一。 :)