使用select来轮询连接 - TCP服务器

时间:2013-04-04 10:35:34

标签: perl sockets

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语句轮询连接。为什么如果我使用无限循环,则不接受连接。它在没有(1)

的情况下工作正常

1 个答案:

答案 0 :(得分:2)

我认为你在这里受到I / O缓冲的困扰。 Perl缓冲所有输入和输出。它通常不会打印到终端,直到它收到整行。

您的代码可能正在使用while(1),但您无法看到调试打印语句的输出,因为正在缓冲输出到终端。一旦你第二次进入循环,$read_select->can_read()将永久阻止,所以你永远不会看到打印语句的输出。

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