Set a timeout on socket_read

你。 提交于 2019-12-30 05:47:19

问题


I was wondering how can I set a timeout on a socket_read call? 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_RCVTIMEO with no luck.

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().


回答1:


this set 5 sec timeout of the socket.

socket_set_option($socket,SOL_SOCKET, SO_RCVTIMEO, array("sec"=>5, "usec"=>0));



回答2:


Have you tried socket_set_option with SO_RCVTIMEO

Timeout value for input operations.




回答3:


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?

UPDATE: I found that setting the socket as nonblocking and then using socket_listen provided the timeout I needed.




回答4:


$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();


来源:https://stackoverflow.com/questions/389645/set-a-timeout-on-socket-read

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!