Socket API and IO::Socket
Perl provides native support for sockets
and a module called Socket to smooth some of the rough edges
associated with the native socket
call. It turns
out that there are still a large number of options to deal with, and
since most applications use a fairly standard set of options, we
instead use a truly convenient module called IO::Socket, which is
built on Socket.
This section uses this module to build a sending and receiving program.
Receiver
Just as you would ask the phone company for a telephone number and a physical handset, both sender and receiver ask the module to create sockets. Sockets, like telephones, are bidirectional endpoints: once a connection is established, either side can send and receive data, as long as there is an understanding between the two programs about the direction of communication.
Because only the receiving side needs to have a well-known address, we create a receiving socket as follows:
use IO::Socket; $sock = new IO::Socket::INET (LocalHost => 'goldengate', LocalPort => 1200, Proto => 'tcp', Listen => 5, Reuse => 1, ); die "Could not connect: $!" unless $sock;
The IO::Socket::INET module provides a nice wrapper for
Internet domain sockets. The LocalHost
and LocalPort
parameters specify the host and port on which this socket is going to listen. The number 1200 is chosen arbitrarily, but you must make sure that it doesn’t conflict with the port number used by some other application on that machine (otherwise, you get an error ...
Get Advanced Perl Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.