0

perlを使用してtcpソケットサーバーを作成しようとしていました。特定のポートをリッスンするサーバーを作成することに成功しました。しかし、1 つのクライアント リクエストを処理した後、ソケット サーバーが閉じられます。サーバーは複数のクライアント要求をリッスンしていません。

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

上記のコードで問題を見つけることができません。誰かがこれについて私を助けてくれませんか?

4

1 に答える 1

0

perlipc(1) の man ページで INET/TCP ソケット サーバーの動作例を見つけることができます。here で説明されているように、IO::Socket標準を使用することを好みます。IO::Socket モジュールを使用したくない場合は、ここに実例があります。

このマニュアルのサーバー サンプル コード:

 #!/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;
 }

それが役に立てば幸い!

于 2013-08-01T20:11:38.600 に答える