5秒后关闭PHP TCP套接字

时间:2015-01-29 19:26:09

标签: php tcp timeout tcpsocket

我创建了一个PHP脚本,它连接到TCP Socket服务器,发送标识,然后将接收不断更新。 (它连接到我的恒温器)然而,目前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);
?>

`

1 个答案:

答案 0 :(得分:1)

套接字已打开,但不会发生异常。您必须在开始读取之前设置套接字读取超时值。

socket_set_option($socket,SOL_SOCKET, SO_RCVTIMEO, array("sec"=>5, "usec"=>0));

如果你不这样做,while循环将一直等到信号永远。