#!/usr/bin/perl # Perl SOPW # https://www.perlmonks.org/?node_id=11151665 use strict; use warnings; $|=1; #Turn stdio buffering off use IO::Socket; use POSIX qw(sys_wait_h); use constant LISTEN_PORT => 8081; my $socket = IO::Socket::INET->new ( LocalPort => 8081, Proto => 'tcp', Type => SOCK_STREAM, Reuse => 1, Listen => 10, ) or die "Could not open port 8081!"; my $client; while (1) { $client = $socket->accept() || next; #accept() is not re-entrant #loop if error my $pid = fork(); die "Bad Fork!" unless defined $pid; if ($pid == 0 ) # child { close ($socket); # children don't listen for new connections my $line; my @buff; while (defined ($line=<$client>) and $line !~ /^\s*$/) { push @buff, $line; } my $time = time(); print "INCOMING from a Client Connection at $time\n"; do_command(\@buff); exit(0); } else # parent { close ($client); #wait for next client request } } sub do_command { my $buff = shift; print $client "START\n"; print $client "$_" for @$buff; #just loopback lines to client print $client "END\n"; $client->flush(); }