Function name: stream_socket_recvfrom()
Function description: The stream_socket_recvfrom() function receives data from the socket and returns the received data.
Applicable version: PHP 5 >= 5.3.0, PHP 7
Syntax: stream_socket_recvfrom ( resource $socket , int $length [, int $flags = 0 [, string &$address ]] ) : string|false
parameter:
- $socket: Required, represents an open socket resource that can be created through the stream_socket_client() or stream_socket_server() function.
- $length: Required, indicating the maximum length of data to be received.
- $flags: Optional, used to specify additional options when receiving data.
- $address: Optional, used to store the sender's IP address and port number.
Return value: Returns the received data when successful, and returns false when failure.
Example:
- Receive data and print:
$socket = stream_socket_client("udp://127.0.0.1:1234", $errno, $errstr); if (!$socket) { echo "Connection failed: $errstr ($errno)"; } else { $data = stream_socket_recvfrom($socket, 1024); echo "Received data: $data"; fclose($socket); }
- Receive data and obtain the sender's IP address and port number:
$socket = stream_socket_server("udp://127.0.0.1:1234", $errno, $errstr, STREAM_SERVER_BIND); if (!$socket) { echo "Failed to start the server: $errstr ($errno)"; } else { $client = stream_socket_accept($socket); $data = stream_socket_recvfrom($client, 1024, 0, $address); echo "Received data: $data"; echo "Sender address: $address"; fclose($client); fclose($socket); }
Notes:
- The stream_socket_recvfrom() function is only suitable for transport protocols that support stream sockets (such as TCP, UDP).
- When using the UDP protocol, you need to specify the "udp://" protocol prefix when creating the socket.
- If the $address parameter is specified, the function stores the sender's IP address and port number in the variable.
- The $length parameter specifies the maximum length of data to be received. If the actual data length received exceeds this value, only part of the data will be returned.
- The $flags parameter can be used to specify options when receiving data. Common options include MSG_WAITALL (wait until the data of the specified length is received) and MSG_DONTWAIT (non-blocking mode).
- Before receiving data, you need to create a socket resource, which can be created using the stream_socket_client() or stream_socket_server() functions.