我创建了一个连接到 TCP 套接字服务器的 PHP 脚本,发送一个标识,然后将接收不断更新。(它连接到我的恒温器)但是目前 PHP 将保持套接字打开,直到它被我的恒温器关闭。如何在 5 秒后从 PHP 脚本自动关闭套接字?
<?php
//Port and IP
$service_port = ('5000');
$address = ('10.0.0.14');
// Create a TCP/IP socket.
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "<br />";
} else {
echo "OK.<br />";
}
echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
echo "socket_connect() failed.<br />Reason: ($result) " . socket_strerror(socket_last_error($socket)) . "<br />";
} else {
echo "OK.<br />";
}
$in .= "{ \"action\": \"identify\", \"options\": {\"core\": 0,\"receiver\": 1,\"config\": 0,\"forward\": 0}, \"media\": \"all\"}";
$out = '';
//Send Message
socket_write($socket, $in, strlen($in));
//Reply
echo "Reading response:<br /><br />";
while ($out = socket_read($socket, 2048)) {
echo $out."<br /><br />";
}
socket_close($socket);
?>
`