Perl on Linux - Iterative, Forking, Multi-Request Handling Server
Every so often you want to do something cool in perl, like make your own server capable of handling multiple requests. And if you are developing any type of network server, this functionality is not only handy, but essential. And so, without much further adieu, let’s do this.
In order to save ourselves much time and annoyance, we are going to use the very standard IO::Socket module to handle the IO stream and sockets.
#! /usr/bin/perl
use strict;
use IO::Socket;
my $server = IO::Socket::INET->new
(
LocalPort => 9876,
Type => SOCK_STREAM,
Reuse => 1,
Listen => 10
)
or die "Unable to create socket.\n";
So first we create the socket with port 9876, make it a socket stream, set it to be reusable, and give it a queue listening size. If we are unable to create the stream, there isn’t much point of continuing (at least in this example) so we die.
my $connect = 0;
print "Waiting for a connection...\n";
while (my $cli = $server->accept())
{
We initialize a variable to keep track of how many connections we have going and then start the while loop that operates as long as we are able to accept a connection.
if(fork() == 0))
{
Once we get a connection, we fork, and if fork == 0 then we know we’re the child process and therefore we will handle the request!
print "Connection received (#$connect)\n";
while(<$cli>)
{
$connect++;
So now we loop through and read the input from the socket
print "recieved $_";
$result = eval ($_);
print "result is $result\n";
print $cli "$result\n";
So we read in the data, eval it, and return the result to the client … wouldn’t ever want to do this for real, but it makes a good example!
}
print "Terminating connection #$connect\n";
exit 0;
We exit now (being the child process).
} print "Waiting for connection #$connect\n"; }
And that’s it! Give it a shot, play around with it. This also works really well with the Daemon Making Tutorial to make a server daemon. Enjoy!



[...] you go! A self restartable, easily killable daemon written in perl! This also works well with the Forking Server Tutorial we have as well. Play with it, have [...]