Function name: socket_accept()
Applicable version: PHP 4 >= 4.1.0, PHP 5, PHP 7
Usage: The socket_accept() function is used to accept a connection request and returns a new socket resource for communicating with the client.
Syntax: resource socket_accept ( resource $socket )
parameter:
Return value: Returns a new socket resource when successful, for communication with the client. Returns FALSE when it fails, and the error code can be obtained through socket_last_error().
Example:
// 创建套接字$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); // 绑定套接字到IP 地址和端口socket_bind($socket, '127.0.0.1', 8080); // 开始监听连接socket_listen($socket); // 接受客户端连接请求$clientSocket = socket_accept($socket); // 与客户端进行通信while (true) { // 从客户端接收数据$data = socket_read($clientSocket, 1024); // 处理数据// 向客户端发送响应socket_write($clientSocket, "Hello, client!"); // 结束通信if ($data === 'quit') { socket_close($clientSocket); break; } } // 关闭套接字socket_close($socket);
In the above example, we create a socket and bind to the local port 8080. Then start listening to the connection through the socket_listen() function. When there is a client connection request, we use socket_accept() to accept the connection and return a new socket resource $clientSocket. Then we enter a loop, receive data from the client through socket_read(), and then process the data and send a response to the client through socket_write(). If the received data is "quit", the connection with the client is closed and communication is terminated. Finally, we use socket_close() to close the socket.