0

最近我正在做一个关于网络连接的项目。我正在 Perl 上制作服务器端程序,它处理来自客户端的请求,处理来自其他服务器的请求数据。出于多用户处理的目的,我必须使用多任务处理。并且为了不泄漏资源,来自客户端的每个线程/连接都有有限的超时时间(5 秒)

这是我的代码:

    while(1)
{
    # waiting for new client connection.
    $client_socket = $socket->accept();
    threads->new(\&gotRequest, $client_socket);

    #gotRequest($client_socket);

}

这是为了从客户端捕获连接

sub gotRequest 
    {
        $client_socket=$_[0];
#       $peer_address = $client_socket->peeraddr();

        $th1=threads->new(\&Responce, $client_socket);
        sleep(5);
        if (!($th1->is_running())) {print "Connection terminated\n";}
        else 
            {
                print "Operation time out, killing process and terminating connection\n";
                print $client_socket "QUIT\n";
                close $client_socket;
                print "Closing...\n";

                #$thr->set_thread_exit_only();
                $th1->detach();
                $th1->exit(); #This thing causing thread's death

                print "Hello I'm still here!";
            }
    }   

这是管理处理线程按时退出的线程,否则服务器无法获得新连接

sub Responce
    {
    $client_socket=$_[0];
    $peer_address = $client_socket->peeraddr();
    $peer_port = $client_socket->peerport();

    sleep (10);
    print "I'm still alive";
    print "Accepted New Client Connection From : $peeraddress, $peerport\n";#Dont know why but this printed null with 2 null string :(

    $client_socket->recv($data,1024000);
    $data_decode = decode("utf-16", $data);
    print "Received from Client : $data_decode\n";

#Custom code added here

    $data = encode("utf-16","DATA from Server");
    print $client_socket "$data\n";
    #close($sock);
    }

我得到了错误:

Thread 1 terminated abnormally: Usage: threads->exit(status) at server-cotton.pl line 61 thread 1

当。。。的时候

$th1->exit();

执行。

还有一件事,我不能不断开与客户端的连接。

4

1 回答 1

1

正如消息所说,这是一个静态方法调用

 threads->exit(1);   # ok

不是实例方法调用

 $th1->exit(1);      # not ok unless $th1 contains the string "threads"
于 2013-06-16T03:38:42.297 回答