最近我正在做一个关于网络连接的项目。我在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->出口();
执行。
还有一件事,我不能断开与客户端的连接。
答案 0 :(得分:1)
正如消息所说,这是一个静态方法调用
threads->exit(1); # ok
不是实例方法调用
$th1->exit(1); # not ok unless $th1 contains the string "threads"