Perl TCP Server处理多个客户端连接

时间:2011-01-31 22:43:00

标签: multithreading perl tcp

我将在前言中说我对Perl和Socket编程的经验都很少,所以我很感激我能得到的任何帮助。我有一个TCP服务器,它需要同时处理多个客户端连接,并且能够随时从任何一个客户端接收数据,并且能够根据收到的信息将数据发送回客户端。例如,Client1和Client2连接到我的服务器。 Client2发送“Ready”,服务器将其解释并向Client1发送“Go”。以下是我到目前为止所写的内容:

my $sock = new IO::Socket::INET 
{
    LocalHost => $host, // defined earlier in code
    LocalPort => $port, // defined earlier in code
    Proto => 'tcp',
    Listen => SOMAXCONN,
    Reuse => 1,
};
die "Could not create socket $!\n" unless $sock;

while ( my ($new_sock,$c_addr) = $sock->accept() ) {
    my ($client_port, $c_ip) = sockaddr_in($c_addr);
    my $client_ipnum = inet_ntoa($c_ip);
    my $client_host = "";

    my @threads;

    print "got a connection from $client_host", "[$client_ipnum]\n";
    my $command;
    my $data;

    while ($data = <$new_sock>) {
        push @threads, async \&Execute, $data;
    }
}

sub Execute {
    my ($command) = @_;

    // if($command) = "test"
    // send "go" to socket1

    print "Executing command: $command\n";
    system($command);
}

我知道我的两个while循环都会被阻塞,我需要一种方法来实现我的接受命令作为一个线程,但我不确定正确的编写方式。

1 个答案:

答案 0 :(得分:5)

fork,thread或使用select进行I / O多路复用。另请查看Net::ServerAnyEvent::Socket。有关I / O多路复用的示例,请查看How can I accept multiple TCP connections in Perl?