in reply to IO::Socket recv and send

Hello milanpwc,

Welcome to the Monastery. This question has been asked and answered before with different approaches (see here How to find out whether socket is still connected?).

Another possible way independent the protocol (UDP / TCP) is the module IO::Socket::INET which has the connected method that you can use before sending the data. For example:

while ( 1 ) { unless ($sock->connected) { $sock->connect($port, $ip) or die $!; } # ... }

Hope this helps, BR.

Seeking for Perl wisdom...on the process of learning...not there...yet!

Replies are listed 'Best First'.
Re^2: IO::Socket recv and send
by milanpwc (Novice) on Mar 26, 2019 at 04:30 UTC
    The connected() method seems to do the trick, but I have two more questions: 1. Do I have to explicitly call it every time before I call send() and recv()? It looks silly. In C, I can immediately tell if the send or recv is successful or not by inspecting the return value. I can also catch SIGPIPE if I need to. 2. What will happen if the peer crashes right after the connected() check and before the send() or recv()? The send() or recv() will still fail and there seems to be no way to avoid this.

      PublicAccess:

      Error checking code often adds a bunch of visual clutter to code. It's all a matter of which tradeoffs you want to make.

      Checking before each send()/recv() is pretty good, but (as you mention) adds clutter. Worse, it won't always work, as you could be disconnected between the check and the following call.

      You could also check only after you receive a null, but only works for recv().

      You mention that in C you could check for SIGPIPE, so if it meets your needs in C, why not use it in your script? The perlvar documentation for %SIG shows how to create a signal handler.

      ...roboticus

      When your only tool is a hammer, all problems look like your thumb.