【问题标题】:Perl nonblocking socketPerl 非阻塞套接字
【发布时间】:2011-08-19 14:30:57
【问题描述】:

我想使用非阻塞套接字连接,但找不到任何示例来理解主要思想。 我需要客户端在连接到服务器时不会阻止程序执行。 现在我有以下代码:

use IO::Socket;
use IO::Select;
use strict;
$|=1;
my $host="10.0.0.12";
my $SELECT = new IO::Select;
print "Connecting...";
my $sock=new IO::Socket::INET (
    PeerAddr => $host,
    PeerPort => 3128,
    Proto => 'tcp',
    Blocking => 0);
    if(!$sock)
    {
        print "Could not create socket: $!n";
    }
    #print "ok\n";
    $SELECT->add($sock);
    my $buf;
    while (1){
    if($sock and $sock->connected())
    {
        print "ok\n";
    }
    while (my @ready=$SELECT->can_read(0.5))
    {
        foreach my $child (@ready)
        {
            if(!sysread($child, $buf, 256))
            {
                $SELECT->remove($child);
                next;
            }

        }
    }
    sleep 1;
}

当套接字连接时,$sock->connected() 返回 true,我可以做点什么。但是如何检查套接字是否超时?如果它无法连接并因超时而关闭,我无法检查!我该怎么做?

添加: 我懂了! 一段代码

if(!sysread($child, $buf, 256))
{
  $SELECT->remove($child);
  next;
}

超时后关闭套接字!

【问题讨论】:

  • lowtek.com/sockets/select.html 基本上解释了这一点。你不在乎它是为 C 而不是 Perl;原理是一样的。
  • 该示例显示了服务器端,据我所知,它不关心超时。在它过期后,套接字就会关闭。我需要客户端,我需要知道它何时关闭。

标签: perl sockets


【解决方案1】:

在套接字的上下文中,“阻塞”与套接字上的读/写操作有关,而不是连接。您有兴趣在套接字连接上设置超时,通常可以使用

Timeout => $max_seconds_to_wait

IO::Socket 构造函数中的参数。

【讨论】:

  • 如果我在 new() 中添加“超时”,那么它会在程序过期时停止运行。现在,如果没有 Timeout,它正是我需要的,new() 立即返回。我已经测试过了。但我需要知道什么时候超时。
猜你喜欢
  • 1970-01-01
  • 2010-10-31
  • 2013-10-15
  • 1970-01-01
  • 1970-01-01
  • 2013-06-03
  • 1970-01-01
  • 1970-01-01
  • 2017-04-18
相关资源
最近更新 更多