Dr. Banana
Dr. Banana

Reputation: 435

Close PHP TCP Socket after 5 sec

I created a PHP script which connects to a TCP Socket server, sends a identification, then will receive constant updates. (It connects to my thermostat) However currently PHP will keep the socket open until it's closed by my thermostat. How can I automaticly close the socket from the PHP script after 5 seconds?

<?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);
?>

`

Upvotes: 0

Views: 2238

Answers (1)

Tam&#225;s Szab&#243;
Tam&#225;s Szab&#243;

Reputation: 348

Sockets are open, while an exception is not occur. You have to set a socket read timeout value before you starts to read it.

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

If you dont do this, while loop will wait until forever for a signal.

Upvotes: 2

Related Questions