This article mainly introduces the socket connection and read-write data timeout in PHP, analyzes the socket connection settings and the use of skills, the need for friends can refer to the next
This paper describes the socket connection and read-write data timeout in PHP. Share to everyone for your reference, as follows:
Although the Fsockopen () method in PHP has a timeout parameter that connects to the socket, there is no read-write timeout parameter setting for the data after a successful connection in C. No problem, PHP provides a series of methods for stream to prevent timeouts
Stream_set_blocking ($FP, False)
Set the data stream to block mode to prevent data from exiting when it is not finished reading
If the mode is false, the given socket descriptor switches to non-block mode, and if true, switches to block mode. This effect is similar to the fgets () 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 time-out, which should be added immediately after the connection is successfully established, followed by the parameter units in seconds
Stream_get_meta_data ($FP)
Gets the header/metadata from the encapsulated protocol file pointer, returning an array with the format:
Array ( [Stream_type] = Tcp_socket [mode] = r+ [unread_bytes] = 0 [seekable] = [ Timed_out] = [blocked] = 1 [EOF] =)
Where the index timed_out is the timeout information, time-out is true, no time-out is false, we can determine whether the socket timeout, it should be noted that this sentence should be added to each waiting statement, such as Fwrite (), Fread (), and every read, All you have to do is decide if you want to time out, and you only need a timeout setting for a connection stream_set_timeout ($FP, 10).
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 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; }}