Current Location: Home> Function Categories> socket_read

socket_read

Read maximum length bytes from socket
Name:socket_read
Category:Sockets
Programming Language:php
One-line Description:Receive data from socket

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:

  • $socket: Required, a valid socket resource created by socket_create() or socket_accept() functions.
  • $length: Required, the maximum number of bytes to be read.
  • $type: optional, the type of data to be read. The default is PHP_BINARY_READ, which means reading data in binary mode. It can also be specified as PHP_NORMAL_READ, indicating that data is read in normal text.

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.

Similar Functions
Popular Articles