It is very simple tcp server which receive client request,and print it on STDOUT,for every connection,it fork a child sub-process which read a line from socket and then print it on STDOUT on server side.
tcp server source code
#!/usr/bin/perl
use 5.006;
use strict;
use warnings;
use IO::Socket;
use POSIX 'WNOHANG';
use constant PORT => 12000;
my $quit = 0;
#add INT for INT & CHLD
$SIG{INT} = sub{$quit++};
$SIG{CHLD} = sub{
while(waitpid(-1,WNOHANG) > 0) {
}
};
my $listen_socket = IO::Socket::INET->new(LocalPort => PORT,
Listen => 20,
Poto => 'tcp',
Reuse => 1,
Timeout => 60 * 60
);
die "can not create a listen_socket:$@" unless $listen_socket;
warn "server ready,waiting for connection.../n";
#main loop,accept client request and fork a child
while(!$quit){
next unless my $connection = $listen_socket->accept;
defined(my $child = fork()) or die "can not fork:$!";
if($child == 0){
$listen_socket->close;
print "child process/n";
process_client_request($connection);
exit 0;
}
$connection->close;
}
#print client request!
sub process_client_request{
my $sock = shift;
while(<$sock>){
chomp;
print $_ . "/n";
}
}
tcp client read from STDIN until you press CTRL + D
client source code
#!/usr/bin/perl
#read from STDIN and send string to server
#client request until you terminate
use strict;
use IO::Socket;
use warnings;
my $host = "localhost";
my $port = 12000;
$SIG{INT} = sub{exit};
my $sock = IO::Socket::INET->new("$host:$port");
while(defined(my $msg = STDIN->getline)){
print $sock $msg;
}
$sock->close;