gpt4 book ai didi

php - PHP设置套接字超时不起作用?

转载 作者:行者123 更新时间:2023-12-03 11:51:44 27 4
gpt4 key购买 nike

我正在尝试在下面的php函数上设置超时以避免页面加载花费一段时间,但是我需要在页面加载时通过php将tcp消息发送到ip和端口,如何设置超时以防ip和端口不可达?

我已经尝试过使用下面的socket_set_option方法,但是不幸的是,它最多需要30秒,有时甚至更长。

我在laravel 5.2项目中使用了它

public static function send($command, $data = '')
{
$MUSdata = $command . chr(1) . $data;
$socket = \socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));

$connect_timeval = array(
"sec"=>0,
"usec" => 100
);

\socket_set_option(
$socket,
SOL_SOCKET,
SO_SNDTIMEO,
$connect_timeval
);

\socket_connect($socket, Config::get('frontend.client_host_ip'), Config::get('frontend.mus_host_port'));
\socket_send($socket, $MUSdata, strlen($MUSdata), MSG_DONTROUTE);
\socket_close($socket);
}

最佳答案

我基于Brian的comment编写了一个connect_with_timeout函数:

Unfortunately, SO_SNDTIMEO does not affect the connection timeout; only write operations after the socket is connected. You will need to put the socket in nonblocking mode, write your own timeout loop for the connect (which will return EAGAIN until the socket connects), and then put the socket back into blocking mode.



如果套接字及时连接,则该函数返回true,否则返回false。 $timeout是超时时间(以秒为单位), $con_per_sec是每秒尝试连接的次数。
function connect_with_timeout($soc, $host, $port, $timeout = 10) {
$con_per_sec = 100;
socket_set_nonblock($soc);
for($i=0; $i<($timeout * $con_per_sec); $i++) {
@socket_connect($soc, $host, $port);
if(socket_last_error($soc) == SOCKET_EISCONN) {
break;
}
usleep(1000000 / $con_per_sec);
}
socket_set_block($soc);
return socket_last_error($soc) == SOCKET_EISCONN;
}

在Windows和Linux上测试,PHP 5.x

关于php - PHP设置套接字超时不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43854499/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com