在perl中服务客户端后,套接字连接关闭

时间:2013-08-01 16:20:46

标签: perl sockets

我正在尝试使用perl创建一个tcp套接字服务器。我成功地创建了一个侦听特定端口的服务器。但在提供一个客户端请求后,Socket服务器将关闭。服务器没有侦听多个客户端请求。

while (accept(Client, Server)) {
    # do something with new Client connection
    if ($kidpid = fork) {
            close Client;         # parent closes unused handle
            #next REQUEST;
            next REQUEST if $!{EINTR};
    }
    print "$kidpid\n";
    defined($kidpid)   or die "cannot fork: $!" ;

    close Server;             # child closes unused handle

    select(Client);           
    $| = 1;                  ]
    select (STDOUT);

    # per-connection child code does I/O with Client handle
    $input = <Client>;
    print Client "output11\n";  # or STDOUT, same thing

    open(STDIN, "<<&Client")    or die "can't dup client: $!";
    open(STDOUT, ">&Client")    or die "can't dup client: $!";
    open(STDERR, ">&Client")    or die "can't dup client: $!";


    print "finished\n";    

    close Client;
        exit;
}

我无法在上面的代码中找到问题。有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:0)

您可以在perlipc(1)手册页中找到INET / TCP套接字服务器的工作示例。我更喜欢使用描述为here的IO :: Socket标准。如果您不想使用IO :: Socket模块,那么您可以使用示例here

本手册中的服务器示例代码:

 #!/usr/bin/perl -w
 use IO::Socket;
 use Net::hostent;      # for OOish version of gethostbyaddr

 $PORT = 9000;          # pick something not in use

 $server = IO::Socket::INET->new( Proto     => "tcp",
                                  LocalPort => $PORT,
                                  Listen    => SOMAXCONN,
                                  Reuse     => 1);

 die "can't setup server" unless $server;
 print "[Server $0 accepting clients]\n";

 while ($client = $server->accept()) {
   $client->autoflush(1);
   print $client "Welcome to $0; type help for command list.\n";
   $hostinfo = gethostbyaddr($client->peeraddr);
   printf "[Connect from %s]\n", $hostinfo ? $hostinfo->name : $client->peerhost;
   print $client "Command? ";
   while ( <$client>) {
     next unless /\S/;       # blank line
     if    (/quit|exit/i)    { last                                      }
     elsif (/date|time/i)    { printf $client "%s\n", scalar localtime() }
     elsif (/who/i )         { print  $client `who 2>&1`                 }
     elsif (/cookie/i )      { print  $client `/usr/games/fortune 2>&1`  }
     elsif (/motd/i )        { print  $client `cat /etc/motd 2>&1`       }
     else {
       print $client "Commands: quit date who cookie motd\n";
     }
   } continue {
      print $client "Command? ";
   }
   close $client;
 }

希望它有所帮助!