简体   繁体   English

如何停止在Perl中的HTTP :: Daemon端口上侦听

[英]How to stop listening on an HTTP::Daemon port in Perl

I have a basic perl HTTP server using HTTP::Daemon . 我有一个使用HTTP :: Daemon的基本perl HTTP服务器。 When I stop and start the script, it appears that the port is still being listened on and I get an error message saying that my HTTP::Daemon instance is undefined. 当我停止并启动脚本时,似乎仍在侦听该端口,并且收到一条错误消息,指出我的HTTP :: Daemon实例未定义。 If I try to start the script about a minute after it has stopped, it works fine and can bind to the port again. 如果我尝试在脚本停止运行大约一分钟后启动它,它可以正常工作并且可以再次绑定到端口。

Is there any way to stop listening on the port when the program terminates instead of having to wait for it to timeout? 程序终止时,有什么方法可以停止监听端口,而不必等待超时?

 use HTTP::Daemon;
 use HTTP::Status;

 my $d = new HTTP::Daemon(LocalAddr => 'localhost', LocalPort => 8000);

 while (my $c = $d->accept) {
    while (my $r = $c->get_request) {
       $c->send_error(RC_FORBIDDEN)
    }
    $c->close;
    undef($c);
 }

EDIT: 编辑:

As per DVK's response, I tried calling $d->close() but am still getting the same error when trying to restart my script. 根据DVK的响应,我尝试调用$d->close()但在尝试重新启动脚本时仍然遇到相同的错误。

END { $d->close(); }
$SIG{'INT'} = 'CLEANUP';
$SIG{__WARN__} = 'CLEANUP';
$SIG{__DIE__} = 'CLEANUP';

sub CLEANUP {
    $d->close();
    undef($d);
    print "\n\nCaught Interrupt (^C), Aborting\n";
    exit(1);
}

I found a solution to my problem by setting ReuseAddr => 1 when creating the HTTP::Daemon. 通过在创建HTTP :: Daemon时设置ReuseAddr => 1 ,找到了解决问题的方法。

my $d = new HTTP::Daemon(
    ReuseAddr => 1, 
    LocalAddr => 'localhost', 
    LocalPort => 8000);

Did you try $d->close() at the end of the program? 您是否在程序结尾尝试了$d->close()

If not, try that. 如果没有,请尝试。 It's not documented in HTTP::Daemon POD example but the method should be available (inherited from IO::Socket ) 没有在HTTP :: Daemon POD示例中进行记录,但是该方法应该可用(从IO :: Socket继承)

Remember that you might need to be creative about where to call it, eg it might need to go into __DIE__ handler or END {} block 请记住,您可能需要对调用它的位置进行创新,例如,可能需要进入__DIE__处理程序或END {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM