PHP Socket connection and read/write data timeout analysis, phpsocket
This article describes Socket connection and data read/write timeout in PHP. We will share this with you for your reference. The details are as follows:
Although the fsockopen () method has a socket connection timeout parameter in PHP, there is no read/write timeout parameter setting similar to that in C after the connection is successful. It doesn't matter. PHP provides a series of methods for stream to prevent timeout.
stream_set_blocking( $fp , false )
Set the data stream to the blocking mode to prevent the data from exiting after reading the data.
If the mode is false, the specified socket descriptor is switched to the non-block mode. If the mode is true, the socket descriptor is switched to the block mode. this effect is similar to the case where fgets () is read from the socket. in non-block mode, fgets () will return immediately, while in block mode, it will wait for the data to meet the requirements.
stream_set_timeout( $fp , 10 )
Set timeout. This sentence should be added immediately after the connection is established successfully. The unit of the following parameter is second.
stream_get_meta_data( $fp )
Get the header/metadata from the encapsulation protocol file pointer and return an array in the format:
Array( [stream_type] => tcp_socket [mode] => r+ [unread_bytes] => 0 [seekable] => [timed_out] => [blocked] => 1 [eof] =>)
The index timed_out indicates the timeout information, the timeout value is true, and the timeout value is false. We can determine whether the socket timed out, it should be noted that this sentence should be added after each statement that needs to wait, such as fwrite () and fread (), and should be judged whether to time out each read, for a connection, you only need to set stream_set_timeout ($ fp, 10) for one time-out.
Code:
$ Fp = @ fsockopen ($ ip, $ port, $ errNo, $ errstr, 30); if (! $ Fp) {return false;} else {stream_set_timeout ($ fp, 3); // send data fwrite ($ fp, $ packet); $ status = stream_get_meta_data ($ fp ); // sending data timeout if ($ status ['timed _ out']) {echo "Write time out"; fclose ($ fp); return false ;} // read data $ buf = fread ($ fp, 16); $ status = stream_get_meta_data ($ fp ); // Read data timeout if ($ status ['timed _ out']) {echo "Read time out"; fclose ($ fp); return false ;}}