PHP - 如何测试stream_socket_client创建的流是否是开放和可写的?

My question is very similar to this question but in my case I am wanting to know if the stream returned by stream_socket_client is open and writeable.

I know that stream_socket_client will return FALSE if the stream could not be opened, but I am needing to detect later on if the stream has been closed by the server (or closed due to some network error, for example).

At the moment I'm just doing...

$fp = stream_socket_client($apns_url, $error_code, $error_string, $timeout_secs, STREAM_CLIENT_CONNECT, $ctx); //looping through / sending data if (!fp) { //re-open connection }

...but I'm not sure if my if (!fp) {...} check is sufficient?

Use stream_get_meta_data for checking if stream is writable.

 $meta = stream_get_meta_data($fp);

 if(is_writable($meta['uri'])) { 
 // stream is writable
 }

Use feof for checking if stream is open.

  • Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout);

Try checking for end of file instead of checking if it is false

while (!feof($fp)) {...}