in reply to Timeouts in IO::Socket
When you launch client.pl on its own, it tries to connect to TCP port 8000, but there is nothing listening, so the server OS immediately responds with a TCP packet with the RST flag set (at least on my Linux system), which results in the TCP connection attempt to abort with the error "Connection refused" - the timeout doesn't apply because there is a response coming from the server, albeit a negative one. On Windows, the error code 10061 is WSAECONNREFUSED - from here: "No connection could be made because the target computer actively refused it. This usually results from trying to connect to a service that is inactive on the foreign host—that is, one with no server application running."
You could implement the retry yourself, the following works for me, you could adapt this as you like:
use warnings; use strict; use IO::Socket; my $socket; for (1..10) { $socket = IO::Socket::INET->new(Proto => 'tcp', PeerAddr => 'localhost', PeerPort => 8000, Timeout => 10); last if defined $socket; print "Not connected, retrying...\n"; sleep 1; } die "Connection failed" unless defined $socket; print "Client connected\n";
Updated: Minor tweaks to text and code.
Update 2: Actually, the above code can wait for up to 100 seconds total (10 times the Timeout value). You might want to use a time-based loop instead, in the following I've also made the logic and messages a little bit nicer:
use warnings; use strict; use IO::Socket; my $CONN_TIMEOUT_SEC = 10; my $socket; my $startt = time; my $attempt = 1; while ( time - $startt < $CONN_TIMEOUT_SEC ) { sleep 1 if $attempt > 1; print "Connection attempt ", $attempt++, "...\n"; $socket = IO::Socket::INET->new( Proto => 'tcp', PeerAddr => 'localhost', PeerPort => 8000, Timeout => $CONN_TIMEOUT_SEC); last if defined $socket; } die "Connection failed" unless defined $socket; print "Client connected\n";
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Timeouts in IO::Socket (updated)
by Stamm (Sexton) on Jun 23, 2019 at 15:12 UTC |