Function name: socket_read()
Applicable versions: All versions of PHP
Usage: The socket_read() function is used to receive data from a socket. It can read data of a specified length at one time, or read until the specified end character is encountered.
grammar:
string socket_read ( resource $socket , int $length [, int $type = PHP_BINARY_READ ] )
parameter:
Return value: Returns the read data (string type) when successful, and returns false when failure.
Example:
// 创建一个TCP/IP 套接字$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); // 连接到服务器$result = socket_connect($socket, '127.0.0.1', 8080); // 从套接字中读取数据(以二进制方式) $data = socket_read($socket, 1024); if ($data === false) { // 读取失败echo "读取数据失败:" . socket_strerror(socket_last_error($socket)); } else { // 读取成功echo "读取的数据:" . $data; } // 关闭套接字socket_close($socket);
In the above example, we first create a TCP/IP socket and then connect to the server using the socket_connect() function. Next, we use the socket_read() function to read up to 1024 bytes of data from the socket (in binary fashion). If the reading is successful, we print out the read data; if the reading fails, we print out the error message.
Note: In actual use, the parameters need to be adjusted appropriately and the read data need to be processed according to specific business needs.