在发送数据之前检查插座是否已连接

时间:2016-09-12 09:47:01

标签: perl io-socket

我在perl中使用套接字连接编写一个简单的代码:

$sock = new IO::Socket::INET(
                  PeerAddr => '192.168.10.7',
                  PeerPort => 8000,
                  Proto    => 'tcp');
$sock or die "no socket :$!";

然后使用循环发送数据:

while...
print $sock $str;
...loop

有没有办法在循环中插入一个检查连接的命令? 类似的东西:

while...
   socket is up?
   yes => send data
   no => connect again and the continue with loop
...loop

编辑添加我的代码:

my $sock = new IO::Socket::INET(
                    PeerAddr => '192.168.10.152',
                    PeerPort => 8000,
                    Proto    => 'tcp');
  $sock or die "no socket :$!";

  open(my $fh, '<:encoding(UTF-8)', 'list1.txt')
      or die "Could not open file $!";

  while (my $msdn = <$fh>) {
        my $port="8000";
        my $ip="192.168.10.152";
        unless ($sock->connected) {
          $sock->connect($port, $ip) or die $!;
    }
    my $str="DATA TO SEND: " . $msdn;
    print $sock $str;
  }
  close($sock);

1 个答案:

答案 0 :(得分:14)

IO::Socket::INETIO::Socket的子类,其connected method

  

如果套接字处于连接状态,则返回对等地址。如果套接字未处于连接状态,则将返回undef。

如果支票返回undef,您可以在循环中使用该call connect

my $sock = IO::Socket::INET->new(
    PeerAddr => '192.168.10.7',
    PeerPort => 8000,
    Proto    => 'tcp'
);
$sock or die "no socket :$!";

while ( 1 ) {
    unless ($sock->connected) {
        $sock->connect($port, $ip) or die $!;
    }
    # ...
}