我使用Perl脚本来创建TCP服务器。它工作正常,但我需要修改它,以便它接受多个连接。这是我使用的代码:
use IO::Socket::INET;
# auto-flush on socket
$| = 1;
# creating a listening socket
my $socket = new IO::Socket::INET (
LocalHost => '0.0.0.0',
LocalPort => '5000',
Proto => 'tcp',
Listen => 5,
Reuse => 1
);
die "cannot create socket $!\n" unless $socket;
print "server waiting for client connection on port 5000\n";
while(1)
{
# waiting for a new client connection
my $client_socket = $socket->accept();
# get information about a newly connected client
my $client_address = $client_socket->peerhost();
my $client_port = $client_socket->peerport();
print "connection from $client_address:$client_port\n";
# read up to 1024 characters from the connected client
my $data = ":123456F#";
$client_socket->send($data);
# write response data to the connected client
$data = "";
$client_socket->recv($data, 1024);
print "received data: $data\n";
# notify client that response has been sent
shutdown($client_socket, 1);
}
$socket->close();
我需要修改上面的代码才能使用多个连接。我真的很感激任何帮助。 感谢
答案 0 :(得分:2)
处理多个套接字有两种主要方法。
第一个是 - 利用IO::Select
- 具有can_read
函数 - 这允许您测试套接字是否有要读取的数据,并且您可以只迭代套接字列表。阅读IO::Select
上的文档,因为它有一个如何正确完成您想要的内容的示例。
另一种方法是并行处理。特别是使用线程或分叉来异步处理$client_socket
。我将引用您:Perl daemonize with child daemons(主要是因为重写并行代码有点复杂,因此可能超出范围)。我建议你可能想要一个'forking'方法,因为它通常更适合并行风格。