Make PHP socket_connect timeout

有些话、适合烂在心里 提交于 2019-12-12 07:06:51

问题


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.

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.

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.

I am clueless.


回答1:


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 sockets and periodically poll the socket to see if the remote host responded.




回答2:


Try setting default_socket_timeout.



来源:https://stackoverflow.com/questions/11881708/make-php-socket-connect-timeout

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