Server-Side Sockets
On the server side, IO::Socket provides a nice wrapper
for creating server sockets. The wrapper encompasses the socket
, bind
, and listen
procedures, while creating a new
IO::Socket object. For example, we can create an Internet-domain
socket with IO::Socket::INET
:
use IO::Socket; $sock = new IO::Socket::INET (LocalAddr => 'maude.ora.com', LocalPort => 8888, Proto => 'tcp', Listen => 5); die "$!" unless $sock;
The parameters for the new socket object determine whether it
is a server or a client socket. Because we’re creating a server
socket, LocalAddr
and LocalPort
provide the address and port to
bind to the socket. The Listen
parameter gives the queue size for the number of client requests
that can wait for an accept
at
any one time.
When the server receives a client request, it calls
the accept
method on the socket
object. This creates a new socket object on which the rest of the
communication can take place:
$new_sock = $sock->accept( );
When communication is finished on both client and server
sockets, they should be destroyed with close
. If a socket is not properly closed,
the next time you attempt to use a socket with the same name, the
system will complain that the socket is already in use.
Get Perl in a Nutshell, 2nd Edition 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.