This article illustrates the problem of timeout of socket connection and read-write data in PHP. Share to everyone for your reference, specific as follows:
Although the Fsockopen () method in PHP has timeout parameters for connecting sockets, there is no read-write timeout parameter setting for data that is similar to the success of a connection in C. It doesn't matter, PHP provides a series of methods for stream to prevent timeouts
Stream_set_blocking ($FP, False)
Set the data flow to blocking mode to prevent data from not being read out
If the mode is false, the given socket descriptor switches to block mode, and if true, switches to chunk mode. This effect is similar to the case where fgets () is read from the socket. Fgets () in non block mode will be returned immediately, while block mode will wait for the data to meet the requirements.
Stream_set_timeout ($FP, 10)
Set timeout, you should add this sentence immediately after the connection has been successfully established, followed by the parameter units in seconds
Stream_get_meta_data ($FP)
Gets the header/metadata from the encapsulated protocol file pointer and returns an array with the following format:
Array
(
[Stream_type] => tcp_socket
[mode] => r+
[unread_bytes] => 0
[seekable] =>< C12/>[timed_out] =>
[blocked] => 1
[EOF] =>
)
Where the index timed_out is timeout information, timeout is true, no timeout is false, we can determine whether the socket timeout, it should be noted that this sentence should be added after each need to wait for the statement, such as Fwrite (), Fread (), and read each time, To determine whether to timeout at once, and only one timeout for a connection stream_set_timeout ($FP, 10) is OK
Code:
$fp = @fsockopen ($ip, $port, $errNo, $errstr,);
if (! $fp)
{return
false;
}
else
{
stream_set_timeout ($fp, 3);
Send data
fwrite ($FP, $packet);
$status = Stream_get_meta_data ($fp);
Send data timeout
if ($status [' timed_out '])
{
echo "Write Time Out";
Fclose ($FP);
return false;
}
Read
the data $buf = Fread ($fp);
$status = Stream_get_meta_data ($fp);
Read Data timeout
if ($status [' timed_out '])
{
echo "read Time Out";
Fclose ($FP);
return false;
}
}
More interested in PHP related content readers can view the site topics: "PHP Socket Usage Summary", "PHP string (String) Usage summary", "PHP Mathematical Calculation Skills Summary", "PHP object-oriented Program Design Introductory Course", "PHP array" Operation Skills Daquan, "PHP Data structure and algorithm tutorial", "PHP Programming Algorithm Summary", "PHP Regular Expression Usage Summary", and "PHP Common database Operation Skills Summary"
I hope this article will help you with your PHP programming.