I've a problem with php fsockopen command.
I need to open a socket connection on a server to implement a message exchange. If the server does not receive anything from my (client) side, it close the connection after a certain timeout (that I don't know exacty neither I can change).
The question is... how can I know if socket opened some minutes ago is still alive?
This is the script that I use to open connection
$socket = fsockopen("automation.srv.st.com", 7777, $errno, $errstr);
if ($socket === false) {
echo "Unable to open Socket. Error {$errno} : {$errstr}\n";
die();
}
$status = stream_get_meta_data($socket);
print_r($status);
and it print out
Array
(
[stream_type] => tcp_socket/ssl
[mode] => r+
[unread_bytes] => 0
[seekable] =>
[timed_out] =>
[blocked] => 1
[eof] =>
)
then of each message written to the server...
fwrite($socket, $message);
... I receive a feedback within 200ms:
$answer = fread($socket, 1024);
But if my script spends 30 minutes without sending any message to server (because it does not have anything to communicate) then the connection is automatically closed by the server and I cannot understand how I can check it before to re-instantiate a new connection:
If tried with
if ($socket) echo "The socket is still having a valid resource\n";
but this would reply my that $socket is still a valid stream resource
I've tried with
$status = stream_get_meta_data($socket);
print_r($status);
I would get back exactly the same output:
Array (
[stream_type] => tcp_socket/ssl
[mode] => r+
[unread_bytes] => 0
[seekable] =>
[timed_out] =>
[blocked] => 1
[eof] =>
)
I've then tried to read some data before to write something but it blocks on fgets statement:
$result = fgets($socket, 1024); //--- Blocking statement
echo ">".$result."\n";
So, I'm almost stucked. My question is: how can I know if the socket opened with fsockopen command is still alive after a certain period of time or not? Which command do I have to use or which approach you would suggest me to implement?
Thanks anybody would help me!
Ciao, Stefano
I don't know if is the right approach or if it could interest someone, but the unique way I've at the end found to know if the socket is still alive or not is using
feof($socket);
or better...
if (feof($socket) === true) echo "Socket close\n";
neither
get_resource_type($socket);
or
stream_get_meta_data($socket);
would produce the expected behaviour.
Anyway thanks to anyone!
Stefano
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With