[NPWP笔记]Develop a multi-process server with perl

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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值