Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php fsockopen how to know if connection is alive

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

like image 861
Stefano Radaelli Avatar asked Dec 02 '13 17:12

Stefano Radaelli


1 Answers

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

like image 109
Stefano Radaelli Avatar answered Nov 12 '22 14:11

Stefano Radaelli