点击(此处)折叠或打开
- #!/usr/bin/perl
- # tcp_iosocket_dt_srv.pl
- use strict;
- use IO::Socket;
- use POSIX qw(WNOHANG);
- $SIG{CHLD} = sub {
- while((my $pid = waitpid(-1, WNOHANG)) >0) {
- print "Reaped child $pid\n";
- }
- };
- #my $zombies = 0;
- #$SIG{CHLD} = sub {$zombies++;};
- my $port = $ARGV[0] || '3000';
- my $sock = IO::Socket::INET->new( Listen => 20,
- LocalPort => $port,
- Timeout => 60*1,
- Reuse => 1)
- or die "Can't create listening socket: $!\n";
- warn "Starting server on port $port...\n";
- while (1) {
- next unless my $session = $sock->accept;
- defined (my $pid = fork) or die "Can't fork: $!\n";
- if($pid == 0) {
- my $peer = gethostbyaddr($session->peeraddr,AF_INET) || $session->peerhost;
- my $port = $session->peerport;
- warn "Connection from [$peer,$port]\n";
- $session->autoflush(1);
- #print $session (my $s = localtime), "\n";
- #print $session "OK shumeiShumei2018\n";
- sysread $session, my $handshake_req,1024;
- print "First req: $handshake_req\n";
- my($handshake_resp) = handshake($handshake_req);
- print "resp: $handshake_resp\n";
- print $session $handshake_resp;
- warn "Connection from [$peer,$port] finished\n";
- close $session;
- exit 0;
- }else {
- print "Forking child $pid\n";
- }
- close $sock;
- ### sub routines
- #
- sub handshake {
- my $req = shift;
- if ( $req =~ /sentry/) {
- return ("OK sentry");
- } elsif ( $req =~ /saas/ ) {
- return ("OK saas");
- } elsif ( $req =~ /data/ ) {
- return ("OK data");
- } elsif ( $req =~ /his/ ) {
- return ("OK his");
- } elsif ( $req =~ /bill/ ) {
- return ("OK bill");
- } else {
- return ("OK shumeiShumei2016");
- }
- return ("req:$req");
- }