点击(此处)折叠或打开

  1. #!/usr/bin/perl
  2. # tcp_iosocket_dt_srv.pl
  3. use strict;
  4. use IO::Socket;
  5. use POSIX qw(WNOHANG);

  6. $SIG{CHLD} = sub {
  7.      while((my $pid = waitpid(-1, WNOHANG)) >0) {
  8.           print "Reaped child $pid\n";
  9.       }
  10. };


  11. #my $zombies = 0;
  12. #$SIG{CHLD} = sub {$zombies++;};

  13. my $port = $ARGV[0] || '3000';
  14. my $sock = IO::Socket::INET->new( Listen => 20,
  15.                                   LocalPort => $port,
  16.                                   Timeout => 60*1,
  17.                                   Reuse => 1)
  18.   or die "Can't create listening socket: $!\n";

  19. warn "Starting server on port $port...\n";
  20. while (1) {
  21.      next unless my $session = $sock->accept;
  22.      defined (my $pid = fork) or die "Can't fork: $!\n";



  23.      if($pid == 0) {
  24.           my $peer = gethostbyaddr($session->peeraddr,AF_INET) || $session->peerhost;
  25.           my $port = $session->peerport;
  26.           warn "Connection from [$peer,$port]\n";
  27.           $session->autoflush(1);
  28.           #print $session (my $s = localtime), "\n";
  29.           #print $session "OK shumeiShumei2018\n";
  30.           sysread $session, my $handshake_req,1024;
  31.           print "First req: $handshake_req\n";
  32.           my($handshake_resp) = handshake($handshake_req);
  33.           print "resp: $handshake_resp\n";
  34.           print $session $handshake_resp;
  35.           warn "Connection from [$peer,$port] finished\n";
  36.           close $session;
  37.           exit 0;
  38.       }else {
  39.           print "Forking child $pid\n";
  40.       }
  41. close $sock;

  42. ### sub routines
  43. #
  44. sub handshake {
  45.     my $req = shift;
  46.     if ( $req =~ /sentry/) {
  47.         return ("OK sentry");
  48.     } elsif ( $req =~ /saas/ ) {
  49.         return ("OK saas");
  50.     } elsif ( $req =~ /data/ ) {
  51.         return ("OK data");
  52.     } elsif ( $req =~ /his/ ) {
  53.         return ("OK his");
  54.     } elsif ( $req =~ /bill/ ) {
  55.         return ("OK bill");
  56.     } else {
  57.         return ("OK shumeiShumei2016");
  58.     }
  59.     return ("req:$req");
  60. }

09-04 14:02