bkchris has asked for the wisdom of the Perl Monks concerning the following question:
I am a frequent visitor of the site but first time poster. I'm having an issue with my client not detecting when it no longer has a connection to the server it is connected to. The server is a network device, so I don't have any control of how that operates. The client needs to have a constant connection to the server, listen and parse any output. I am okay with that part; the disconnection is my issue...the client will hang and not reconnect, it must be restarted
I've created a simulation (see below), it is just your basic Perl server and client files. If the client cannot connect to the server at start-up, it will call recursive functions until it is able to create a connection. If the server script is stopped, the client script tries to reconnect until the server script is restarted. If the network connection from the server is removed, the client does not know about it and cannot reconnect without killing and restarting the process.
Is this normal? Is there a way to get around this? Thanks in advance!
server.pl
#!/usr/bin/perl #server.pl use strict; use IO::Socket::INET; $| = 1; #auto flush my ($socket,$client, $peerAddress, $peerPort); $socket = new IO::Socket::INET ( LocalHost => '127.0.0.1', LocalPort => '5000', Proto => 'tcp', Listen => 5, Reuse => 1, ) || die "cannot create socket $!\n"; print "listening for client connection on 3083\n"; while(1) { # waiting for new client connection. $client = $socket->accept(); $peerAddress = $client->peerhost(); $peerPort = $client->peerport(); print "Accepted New Client Connection From: $peerAddress $peerPort +\n"; } $socket->close();
client.pl
#!/usr/bin/perl # client.pl use strict; use IO::Socket::INET; # start connecting to socket &connectToSocket(0); exit; # handles the socket retries and network device output sub connectToSocket() { my $retry = shift; my $localt = localtime(); print "retry\t$retry\n"; $retry++; my $socket = &openSocket($retry); print "TCP Connection Success.\n"; # process input from network device while (<$socket>) { print "$_"; } # reconnect if socket drops &connectToSocket(0); } # creates the socket connection to the network device sub openSocket() { my $retry = shift; my $socket = IO::Socket::INET->new ( Proto => "tcp", PeerAddr => "192.168.1.105", PeerPort => "5000", Timeout => "1", ) || &connectToSocket($retry); $socket->autoflush(1); return $socket; }
|
|---|