开发者

Perl nonblocking socket

I want to use nonblocking socket connection, but can't find any examples for understand th main idea. I need client what will not block program execution when it will connect to server. Now I have the following code:

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)
    {开发者_JAVA百科
        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;
}

When socket connects $sock->connected() return true and I can do something. But how can check socket for timeout? If it can't connect and closed by timeout I can't check that! How can I do it?

Added: Oh, I see! Piece of code

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

closes socket when timeout is expired!


In the context of sockets, "blocking" has to do with reading/writing operations on the socket, not connecting. You are interested in setting a timeout on the socket connection, which you can usually do with a

Timeout => $max_seconds_to_wait

parameter in the IO::Socket constructor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜