加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl – 在发送数据之前检查套接字是否已连接

发布时间:2020-12-15 21:48:44 所属栏目:大数据 来源:网络整理
导读:我在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 有没有办法在循环中插
我在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',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);

解决方法

IO::Socket::INET是 IO::Socket的子类,其具有 connected method.

If the socket is in a connected state the peer address is returned. If the socket is not in a connected state then undef will be returned.

如果检查返回undef,您可以在循环和call connect中使用它.

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读