Chinaunix首页 | 论坛 | 博客
  • 博客访问: 538794
  • 博文数量: 102
  • 博客积分: 950
  • 博客等级: 准尉
  • 技术积分: 1094
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-28 16:07
文章分类

全部博文(102)

文章存档

2020年(2)

2016年(5)

2015年(15)

2014年(25)

2013年(18)

2012年(19)

2011年(18)

我的朋友

分类: PERL

2020-01-20 17:40:38


点击(此处)折叠或打开

  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. }

阅读(1050) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~