gpt4 book ai didi

perl - 发送数据前检查socket是否连接

转载 作者:行者123 更新时间:2023-12-04 05:36:50 25 4
gpt4 key购买 nike

我正在使用 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);

最佳答案

IO::Socket::INETIO::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.



您可以在循环中使用它和 call connect 如果支票返回 undef .
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 $!;
}
# ...
}

关于perl - 发送数据前检查socket是否连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39447554/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com