bengmau has asked for the wisdom of the Perl Monks concerning the following question:

I setup a socket to continuously grab input from a stream until the session is disconnected. I've been told that there is a possibility that a session may stay up but no data will go through or gibberish. There is a particular heartbeat messsage that does come out after xx mins. How can I best check for that? The code I have right now will sit in the while loop until something gets fed in. Will I need to create a fork process to do this to monitor an environment variable or something easier?
my $sock; $sock = IO::Socket::INET->new(PeerAddr => $host, PeerPort => $port, Proto => 'tcp'); open (FILEOUT,">output.log"); my @msgstream; while (<$sock>) { #process line until end of socket stream my $line=$_; if ($line=~/^;/) { # if the line has a ';' in it processmsg(\@msgstream); undef @msgstream; #clear @msgstream } else { # add to msgqueue push @msgstream,$line; } }

Replies are listed 'Best First'.
Re: monitor tcp stream but alert if no info in xx mins
by ikegami (Patriarch) on Jun 29, 2005 at 14:53 UTC
    You could use select instead of <...> to wait for data to appear in the socket. Specify a timeout bigger than XX minutes. If select returns due to timeout, kill the connection. Alternatively, alarm might be of use.
      little unclear on the syntax for select in this context. can you provide a quickie example? Thanks
        oh yeah, I forgot how unfriendly it is. There's an class that helps in this case:
        my $sock = IO::Socket::INET->new(PeerAddr => $host, PeerPort => $port, Proto => 'tcp'); my $sel = IO::Select->new($sock); open (FILEOUT, '>', 'output.log'); my @msgstream; while ($sel->can_read($timeout)) { my $line = <$sock>; ... }

        By the way, this thread discusses how to use a second process.