Php fsockopen how to find out if a connection is alive

I have a problem with php fsockopen command.

I need to open a socket connection on a server to implement messaging. If the server does not receive anything from my (client) side, it closes the connection after a certain timeout (which I do not know for sure, I cannot change).

The question is ... how can I find out if a socket is open a few minutes ago?

This is the script that I use to open the 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 print

 Array ( [stream_type] => tcp_socket/ssl [mode] => r+ [unread_bytes] => 0 [seekable] => [timed_out] => [blocked] => 1 [eof] => ) 

then each message recorded on the server ...

  fwrite($socket, $message); 

... I get feedback within 200 ms:

  $answer = fread($socket, 1024); 

But if my script spends 30 minutes without sending any messages to the server (because it has nothing to communicate), then the connection is automatically closed by the server, and I cannot figure out how I can test it, create a new connection:

If you tried using

 if ($socket) echo "The socket is still having a valid resource\n"; 

but this will answer me that $ socket is still a valid stream resource

I tried with

 $status = stream_get_meta_data($socket); print_r($status); 

I would get exactly the same result:

 Array ( [stream_type] => tcp_socket/ssl [mode] => r+ [unread_bytes] => 0 [seekable] => [timed_out] => [blocked] => 1 [eof] => ) 

Then I tried to read some data before writing anything, but it blocks the fgets statement:

 $result = fgets($socket, 1024); //--- Blocking statement echo ">".$result."\n"; 

So, I'm almost stuck. My question is: how can I find out if a socket is open with the fsockopen command after a certain period of time or not? Which team should I use or what approach would you suggest I implement?

Thank you, someone will help me!

Ciao, Stefano

+6
source share
1 answer

I donโ€™t know if the approach is right or if it might interest someone, but the only way I eventually found out 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); 

will result in the expected behavior.

Anyway, thanks to someone!

Stefano

+2
source

Source: https://habr.com/ru/post/959186/


All Articles