使 PHP socket_connect 超时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11881708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make PHP socket_connect timeout
提问by Axel Latvala
I have a small application I created to analyze the network connection. It runs from a browser and connects to a local PHP/Apache server. It then asks PHP to send a ping packet through a raw socket. THe problem is that if the host I am trying to ping isn't alive or won't answer to pings, we never get an answer from the server.
我创建了一个小应用程序来分析网络连接。它从浏览器运行并连接到本地 PHP/Apache 服务器。然后它要求 PHP 通过原始套接字发送一个 ping 数据包。问题是,如果我尝试 ping 的主机不存在或不响应 ping,我们永远不会从服务器得到答案。
I beleave the socket request lives until apache is restarted. I have been getting mixed results from my application lately and I am blaming apache using too many sockets. Currently I have set the AJAX call's timeout and I was happy with it. But I really need to make PHP do the timeouting so that I won't have 500,000 sockets open to an unreachable host.
我相信套接字请求会一直存在,直到 apache 重新启动。我最近从我的应用程序中得到了好坏参半的结果,我指责 apache 使用了太多的套接字。目前我已经设置了 AJAX 调用的超时时间,我对此很满意。但我真的需要让 PHP 执行超时,这样我就不会向无法访问的主机打开 500,000 个套接字。
Some sample code:
一些示例代码:
$sockconn = @socket_connect($socket, $target, null);
if(!$sockconn)
{
$raw['error'] = socket_strerror(socket_last_error());
$raw['status'] = false;
return $raw;
}
This is the function that won't timeout. I need to get it to timeout. Also PHP script execution time DOES NOT affect sockets.
这是不会超时的功能。我需要让它超时。此外,PHP 脚本执行时间不会影响套接字。
I am clueless.
我一窍不通。
回答by Sjoerd
You can set timeouts for reading and sending using the following options:
您可以使用以下选项设置读取和发送超时:
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 1, 'usec' => 0));
socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 1, 'usec' => 0));
Alternatively, you can use non-blocking socketsand periodically poll the socket to see if the remote host responded.
或者,您可以使用非阻塞套接字并定期轮询套接字以查看远程主机是否响应。
回答by Sjoerd
Try setting default_socket_timeout.

