I'm programming a simple code using socket connection in perl:
$sock = new IO::Socket::INET(
PeerAddr => '192.168.10.7',
PeerPort => 8000,
Proto => 'tcp');
$sock or die "no socket :$!";
Then sending data using a loop:
while...
print $sock $str;
...loop
Is there a way to insert into the loop a command to check connection? Something like:
while...
socket is up?
yes => send data
no => connect again and the continue with loop
...loop
EDIT ADD MY CODE:
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);
The only way to tell if the socket has been disconnected is to send data over it. set the timeout on the server side socket and then have the client check in every so often within the timeout so if you set the client to check in every 10 seconds then set the timeout to say 30 seconds on the server socket.
You can check the socket. connected property: var socket = io. connect(); console.
The most obvious way to accomplish this is having that process call read on the socket for a connection and check whether read returns 0 (i.e. reads zero bytes from the socket), in which case we know that the connection has been closed.
IO::Socket::INET is a subclass of IO::Socket, which has a 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.
You can use that in your loop and call connect
on it if the check returned 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 $!;
}
# ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With