After creating a socket with the socket
function as you did previously, a
server application must go through the following steps to receive
network connections:
We start out by creating a socket for the server:
my $proto = getprotobyname('tcp'), socket(FH, PF_INET, SOCK_STREAM, $proto) || die $!;
The filehandle $FH
is the
generic filehandle for the socket. This filehandle only receives
requests from clients; each specific connection is passed to a
different filehandle by accept
,
where the rest of the communication occurs.
A server-side socket must be bound to a port on the local
machine by passing a port and an address data structure to the
bind
function via sockaddr_in
. The Socket module provides
identifiers for common local addresses, such as localhost and the
broadcast address. Here we use INADDR_ANY
, which allows the system to
pick the appropriate address for the machine:
my $sin = sockaddr_in (80, INADDR_ANY); bind (FH, $sin) || die $!;
The listen
function
tells the operating system that the server is ready to accept
incoming network connections on the port. The first argument is the
socket filehandle. The second argument gives a queue length, in case
multiple clients are connecting to the port at the same time. This
number indicates how many clients can wait for an accept
at one time.
listen (FH, $length);
The accept
function
completes a connection after a client requests and assigns a new
filehandle specific to that connection. The new filehandle is given
as the first argument to accept
,
and the generic socket filehandle is given as the second:
accept (NEW, FH) || die $!;
Now the server can read and write to the filehandle NEW
for its communication with the
client.
3.143.22.23