Lucas Rey
Lucas Rey

Reputation: 467

Check if socket is connected before sending data

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);

Upvotes: 9

Views: 3531

Answers (1)

simbabque
simbabque

Reputation: 54333

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 $!;
    }
    # ...
}

Upvotes: 17

Related Questions