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

Luc*_*Rey 8 perl io-socket

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

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

然后使用循环发送数据:

while...
print $sock $str;
...loop
Run Code Online (Sandbox Code Playgroud)

有没有办法在循环中插入一个命令来检查连接?就像是:

while...
   socket is up?
   yes => send data
   no => connect again and the continue with loop
...loop
Run Code Online (Sandbox Code Playgroud)

编辑添加我的代码:

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);
Run Code Online (Sandbox Code Playgroud)

sim*_*que 15

IO ::插座:: INET是的子类IO ::插座,其中有一个connected方法.

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

如果返回检查,您可以在循环中使用它并调用connectundef.

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 $!;
    }
    # ...
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,但这并不总是足够http://perldoc.perl.org/IO/Socket.html#connected(还应检查` - > write()`的返回值) (2认同)
  • @lucas是的,这是一个错字.但是我的代码只是**的一个例子**无论如何.不要直接复制它.您没有显示足够的代码来制作工作程序,因此您只能获得示例.请在问题中包含完整的代码. (2认同)