Oct 222013
 
Article Perl

A common operation where it is desirable to set a timeout is when a server is communicating with other servers or clients through the network.

The server sends a message to the other servers, and waits for answers. But there might be network issues, or some of the other servers might have become unresponsive for some reason, and this should not block the other communications going on.

In Perl, the IO:Select module implements the functionality required to keep in a wait state until a message is received in one or several sockets, o a set timeout is reached.

The example below shows how to use this module:

First, two UDP sockets “$client1” and “$client2” are created to establish a communication through port 3456 with two servers at IP addresses 192.168.2.4 and 192.168.2.5:

Next, an instance of IO::Select is created, and the two sockets are assigned to it:

Finally, the script enters a loop where the server check the availability of incoming data with a call to “can_read”, with a 60 second timeout.

can_read returns as soon as a message has been received from one of the two clients at port 3456, or when the 60 seconds are elapsed. The return value is an array of sockets that have received a message, and are ready to be read. If the timeout has been reached, the return value is an empty array.

The subroutine “process_message”, called when a message is received, might decide to write an answer to that same socket::

Index of posts related to Perl programming

 Posted by at 8:24 am

 Leave a Reply

(required)

(required)