我有一个PHP脚本,用户可以将OTP作为SMS发送。我使用的短信网关大约需要5-8秒来响应。我不能等那么久。我需要发出请求并立即向用户发送HTML响应。
我使用了curl,它花费的时间太长了,一个短暂的超时会导致连接中断,使网关无法预测。我需要一种方法来发出请求,执行一些例程,最好有选项来验证请求。
发布于 2017-02-12 20:51:14
你使用stream_socket_client()。执行GET请求,然后再获得结果。
用stream_socket_client()提出请求
$host = 'www.example.com';
$path = '/';
$http = "GET $path HTTP/1.0\r\nHost: $host\r\n\r\n";
$stream = stream_socket_client("$host:80", $errno,$errstr, 120,STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT);
if ($stream) {
$sockets[] = $stream; // supports multiple sockets
fwrite($stream, $http);
}
else {
$err .= "$id Failed<br>\n";
} 使用stream_select()获取响应
$timeout = 120;
$buffer_size = 8192;
while (count($sockets)) {
$read = $sockets;
stream_select($read, $write = NULL, $except = NULL, $timeout);
if (count($read)) {
foreach ($read as $r) {
$id = array_search($r, $sockets);
$data = fread($r, $buffer_size);
if (strlen($data) == 0) { // done
fclose($r);
unset($sockets[$id]);
}
else {
$result[$id] .= $data; // append buffer to result
}
}
}
else {
// echo 'Timeout: ' . date('h:i:s') . "\n\n\n";
break;
}
}更新
您可以在任何时候提出请求,并在请求之后的任何时候得到响应。创建套接字时,$sockets数组的键是$id。
如果要使用其他控制方法,则不必使用while循环。示例中的缓冲区为8K。如果响应大于8K,则需要多次读取。
如果您不想检索响应,那么就关闭套接字,不要使用$sockets数组。在fclose()之前,您可能需要或不需要延迟。这取决于主机对丢弃连接的响应方式。
$host = 'www.example.com';
$path = '/?param=value';
$http = "GET $path HTTP/1.0\r\nHost: $host\r\n\r\n";
$stream = stream_socket_client("$host:80", $errno,$errstr, 120,STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT);
if ($stream) {
fwrite($stream, $http);
fclose($stream);
}
else {
$err .= "$id Failed<br>\n";
} https://stackoverflow.com/questions/42190148
复制相似问题