要設置PHP Socket的超時時間,您需要在創建套接字后使用settimeo()
函數
<?php
// 創建一個新的socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!$socket) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
exit();
}
// 設置超時時間(秒)
$timeout = 10;
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, ['sec' => $timeout, 'usec' => 0]);
socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, ['sec' => $timeout, 'usec' => 0]);
// 連接到服務器
$host = '127.0.0.1';
$port = 80;
$result = socket_connect($socket, $host, $port);
if (!$result) {
echo "socket_connect() failed.\nReason: " . socket_strerror(socket_last_error($socket)) . "\n";
exit();
}
// 從服務器接收數據
$buffer = '';
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, ['sec' => $timeout, 'usec' => 0]);
$data = socket_read($socket, 2048, PHP_BINARY_READ);
if ($data === false) {
echo "socket_read() failed.\nReason: " . socket_strerror(socket_last_error($socket)) . "\n";
exit();
}
echo "Received data: {$data}\n";
// 關閉套接字
socket_close($socket);
?>
在這個示例中,我們將超時時間設置為10秒。您可以根據需要更改$timeout
變量的值。