2

该服务器工作正常,但如果我这样做

bash$ (echo -n "abcd" ;sleep 50 ; echo "efgh") | 数控本地主机 9090

服务器阻塞 50 秒。在我的完整代码中,我有多个IO::Select::INET. 我有另一个套接字侦听其他端口(1234),当服务器被睡眠阻塞时,我无法处理该端口中的任何内容。我尝试更改getlinebygetc但我只读取了第一个字母“a”并且它阻塞了。

有人可以帮助我吗?

use common::sense;
use IO::Select;
use IO::Socket;

use constant PORT1 => 9090;
use constant TIMEOUT => 1;

my $event_socket  = new IO::Socket::INET(Listen => 1, LocalPort => PORT1, ReuseAddr => 1) 
    or die "Can't bind event_socket: $@\n";

my $sel = IO::Select->new;
$sel->add($event_socket);

my $event_emiter = undef;

while(1){ 
    foreach my $sock (my @ready = $sel->can_read(TIMEOUT)) {
        if ($sock == $event_socket) {
            my $new = $event_socket->accept;
            binmode($new, ":encoding(UTF-8)");
            $sel->add($new);

            $event_emiter=$new;

            warn "[event socket] connect from ",$new->peerhost, "\n";
        } elsif ($sock == $event_emiter) {
            unless($sock->eof){
                my $recv_data = $sock->getline;
                warn "[event socket] LOL '$recv_data'\n";
            } else {
                $sel->remove($sock);
                $sock->close;
                $event_emiter = undef;
                warn "[socket] disconnect\n";
            }
        } else {

            $sel->remove($sock);
            $sock->close;

            warn "[socket] disconnect\n";
        }
    }   
}
4

2 回答 2

6

您不是在读取可用数据,而是在读取换行符之前一直在读取。始终使用sysread.

改变

    elsif ($sock == $event_emiter) {
        unless($sock->eof){
            my $recv_data = $sock->getline;
            warn "[event socket] LOL '$recv_data'\n";
        } else {
            $sel->remove($sock);
            $sock->close;
            $event_emiter = undef;
            warn "[socket] disconnect\n";
        }
    }

    elsif ($sock == $event_emiter) {
        our $buf; local *buf = \$bufs{$fh};  # alias $buf = $bufs{$fh};

        my $rv = sysread($fh, $buf, 64*1024, length($buf));
        if (!$rv) {
            if (defined($rv)) {  # EOF
                # ... Handle anything left in $buf ...
            } else {  # Error
                # ... Handle error ...
            }

            delete $bufs{$fh};
            $sel->remove($sock);
            $sock->close;
            $event_emiter = undef;
            warn "[socket] disconnect\n";
            next;
        }

        while ($buf =~ s/^(.*)\n//) {
            warn "[event socket] LOL '$1'\n";
        }
    }

my %bufs;在选择循环之外添加。

于 2012-11-24T21:34:05.370 回答
0

它在这里阻塞:

my $recv_data = $sock->getline;

这是因为 getline() 正在阻塞等待\n. 相反,您应该sysread()在单独的缓冲区中组装您的命令。

于 2012-11-24T21:34:53.240 回答