2013-04-04 64 views
2
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)使用select來輪詢連接 - TCP服務器

回答

2

我認爲你在這裏被I/O緩衝咬傷。 Perl緩衝所有輸入和輸出。它一般不會打印到終端,直到它收到整條線路。

您的代碼可能與while(1)一起工作,但由於到終端的輸出被緩衝,所以看不到調試打印語句的輸出。一旦你通過循環第二次,$read_select->can_read()永遠阻止,所以你從來沒有看到打印語句的輸出。

只需在每個打印語句的末尾添加\n即可解決此問題。另一個選項是設置$| = 1;。這會禁用緩衝。有關緩衝的更多信息,請參閱perlvar's discussion of $|

+0

很好。發現! – 2013-04-04 11:07:32