【问题标题】:Make blocking timeout IO::Socket read使阻塞超时 IO::Socket 读取
【发布时间】:2014-02-27 02:37:59
【问题描述】:

我需要通过超时使阻塞套接字读取结束。我阅读了this 的问题,我了解到 IO::Socket::INET 不关注 Timeout 选项,并了解了使用eval/alarm 的解决方案。但我在 Windows 上工作,alarm 不能正常工作。有没有其他解决办法?

【问题讨论】:

  • 你是如何在 Windows 上使用套接字的?
  • timeout 选项是关于建立套接字连接,而不是从已经建立的连接中读取数据。

标签: perl sockets


【解决方案1】:

在从套接字读取之前,使用4-argument version of select 和所需的超时时间来测试要读取的套接字上是否有任何数据可用。

另请参阅 IO::Select 模块,特别是 IO::Select::can_read($timeout) 方法来测试套接字读取是否会阻塞。

例子:

$read_timeout = 5.0; # seconds
$socket = IO::Socket->new( ... );     # socket to read from

$selector = IO::Select->new;
$selector->add( $socket );

...

@ready = $selector->can_read( $read_timeout );
if (@ready > 0) {
    $socket->read( $buffer, 128 );   # copy 128 bytes into $buffer
} else {
    warn "data not available on socket now";
}

【讨论】:

    猜你喜欢
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多