php 在 socket_read 上设置超时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/389645/
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
Set a timeout on socket_read
提问by James Hartig
I was wondering how can I set a timeout on a socket_readcall? The first time it calls socket_read, it waits till data is sent, and if no data is sent within 5 secs I want to shutdown the connection. Any Help? I already tried SO_RCVTIMEOwith no luck.
我想知道如何设置socket_read通话超时?第一次调用时socket_read,它会等待直到发送数据,如果在 5 秒内没有发送数据,我想关闭连接。任何帮助?我已经尝试SO_RCVTIMEO过但没有运气。
I'm creating a socket with socket_create()and listening on it for connections, then when connected I listen for the data and then do something with it. When the timeout hits, I want to run socket_shutdown()and then socket_close().
我正在创建一个套接字socket_create()并监听它的连接,然后当连接时我监听数据然后用它做一些事情。当超时到达时,我想运行socket_shutdown()然后socket_close().
采纳答案by James Hartig
I did a socket_listen and then I made a manual timeout with time()+2 and a while loop with nonblock set and socket_read() inside. Seems to be working ok. Any alternatives?
我做了一个 socket_listen 然后我用 time()+2 和一个带有 nonblock set 和 socket_read() 的 while 循环手动超时。似乎工作正常。任何替代方案?
UPDATE: I found that setting the socket as nonblocking and then using socket_listen provided the timeout I needed.
更新:我发现将套接字设置为非阻塞,然后使用 socket_listen 提供了我需要的超时。
回答by Nick
this set 5 sec timeout of the socket.
这设置了套接字的 5 秒超时。
socket_set_option($socket,SOL_SOCKET, SO_RCVTIMEO, array("sec"=>5, "usec"=>0));
回答by OIS
Have you tried socket_set_optionwith SO_RCVTIMEO
您是否尝试过socket_set_option与SO_RCVTIMEO
Timeout value for input operations.
输入操作的超时值。
回答by Konstantin Ermolaev
$read_socket = socket_select($read, $write = NULL, $except = NULL, 10); // 10 - Timeout
if($read_socket === FALSE)
$this->End();
elseif($read_socket === 0)
return FALSE;
$pdu_ = socket_read($this->session, 102400);
if($read_socket && !strlen($pdu_))
$this->End();

