Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if socket is connected before sending data

Tags:

perl

io-socket

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);
like image 990
Lucas Rey Avatar asked Sep 12 '16 09:09

Lucas Rey


People also ask

How do I know if a socket is open?

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.

How do you check socket is connected or not socket IO?

You can check the socket. connected property: var socket = io. connect(); console.

How do you know if a socket is closed?

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.


1 Answers

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 $!;
    }
    # ...
}
like image 53
simbabque Avatar answered Oct 11 '22 06:10

simbabque