February 2012
Intermediate to advanced
1184 pages
37h 17m
English
Here’s a corresponding server to go along with it. It’s pretty easy with the
standard IO::Socket::INET class:
use IO::Socket::INET;
$server = IO::Socket::INET–>new(LocalPort => $server_port,
Type => SOCK_STREAM,
Reuse => 1,
Listen => 10 ) # or SOMAXCONN
|| die "Couldn't be a tcp server on port $server_port: $!\n";
while ($client = $server–>accept()) {
# $client is the new connection
}
close($server);You can also write that using the lower-level Socket module:
#!/usr/bin/env perl
use v5.14;
use warnings;
use autodie;
use Socket;
my $server_port = 12345; # pick a number
# make the socket
socket(my $server, PF_INET, SOCK_STREAM, getprotobyname("tcp"));
# so we can restart our server quickly
setsockopt($server, SOL_SOCKET, SO_REUSEADDR, 1);
# build up my socket address
my $own_addr = sockaddr_in($server_port, INADDR_ANY);
bind($server, $own_addr);
# establish a queue for incoming connections
listen($server, SOMAXCONN);
# accept and process connections
while (accept(my $client, $server)) {
# do something with new client connection in $client
} continue {
close $client;
}
close($server);The client doesn’t need to bind
to any address, but the server does. We’ve specified its address as
INADDR_ANY, which means that clients
can connect from any available network interface. If you want to sit on
a particular interface (like the external side of a gateway or firewall
machine), use that interface’s real address instead. (Clients can also
do this, but they rarely need to.)
Read now
Unlock full access