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

I'm trying to write a simple TCP server that will wait for a poll message and respond, or a data message and process. This all looks fine, what I now need to add is a timeout so if no poll is received in 3 minutes to do something.

Is there a nice simple way to do this? Help with knowing what to look for will probably surfice.

I'm using IO::Socket::INET on Solaris. I don't need much in the way of error handling or handshaking. It really is very simple.

Thanks in advance.

Replies are listed 'Best First'.
Re: TCP Server timeout
by jethro (Monsignor) on Feb 22, 2010 at 23:07 UTC
    There is a timeout parameter you can pass to IO::Socket::INETs constructor (at least in the current version).

    And there is IO::Socket::INET::Daemon, a simple tcp daemon, also with a timeout parameter. ...Daemon seems to be dependent only on IO::Socket::INET and IO::Select.

    And you might use IO::Select directly to add a timeout to your server code.

Re: TCP Server timeout
by leighsharpe (Monk) on Feb 23, 2010 at 03:59 UTC
    The 'timeout' option to IO::Socket will do what you want:
    #!/usr/bin/perl use strict; use warnings; use IO::Socket; my $server=IO::Socket->new( Domain=>AF_INET, Proto=>'tcp', LocalPort=>'1234', Listen=>SOMAXCONN, ); $server->timeout(10); my $connection=$server->accept; if ($connection) { print "Got a message.\n"; close $connection; } else { print "Timed out.\n"; }
Re: TCP Server timeout
by Khen1950fx (Canon) on Feb 22, 2010 at 23:53 UTC
    As I understand it, timeout would apply to the connection handshake, not waiting for a poll or data message. Also, I checked the source for IO::Socket::INET, and the timeout function is commented out. You could still try adding a timeout to the constructor, but I don't know if that would work or not. I'd go with jethro's advice and use IO::Socket::INET::Daemon. It's the simplest way that I know of.