gpt4 book ai didi

perl - 使用选择轮询连接-TCP服务器

转载 作者:行者123 更新时间:2023-12-03 11:53:15 28 4
gpt4 key购买 nike

use strict; use warnings;
use IO::Socket;
use IO::Select;
my $read_select = IO::Select->new();
my $write_select = IO::Select->new();

my $socket = IO::Socket::INET->new(
LocalHost => '127.0.0.1',
LocalPort => '5556',
Proto => 'tcp',
Listen => 50,
Reuse => 1,
) or die "Could not create socket: $!";

print "Socket Created . Waiting for connection ...\n";

## poll to accept new connection or to receive data from a connection

$read_select->add($socket);

print "Added socket to read list ";
my $reade;
my $newconn;
my @read;
my @write;
while(1) {
@read = $read_select->can_read();

foreach my $reade(@read) {
if($reade == $socket) {
print "New conn received";
my $newconn = $reade->accept();
$write_select->add($newconn);

}
else {
print "data received";
}
}
}
@write = $write_select->can_write();

foreach my $write(@write) {
$write->send("got ur data");
}

我正在尝试使用select语句轮询连接。为什么如果我使用无限循环,则不接受任何连接。没有while(1)即可正常工作

最佳答案

我认为您在这里被I/O缓冲所困扰。 Perl缓冲所有输入和输出。在收到整行之前,它通常不会打印到终端上。

您的代码可能与while(1)一起使用,但是您看不到调试打印语句的输出,因为终端的输出正在缓冲中。一旦您进入第二次循环,$read_select->can_read()就会永远阻塞,因此您永远不会看到print语句的输出。

您可能只需在每个print语句的末尾添加\n即可解决此问题。另一种选择是设置$| = 1;。这将禁用缓冲。有关缓冲的更多信息,请参见perlvar's discussion of $|

关于perl - 使用选择轮询连接-TCP服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15808781/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com