Function name: stream_socket_accept()
Function Applicable Version: PHP 4 >= 4.1.0, PHP 5, PHP 7
Function description: The stream_socket_accept() function accepts a socket connection created by the stream_socket_server() function and returns a new socket connection for communication with the client.
Syntax: resource stream_socket_accept ( resource $server_socket [, float $timeout = ini_get("default_socket_timeout") [, string &$peername ]] )
parameter:
Return value: If a client connection is successfully accepted, a new socket resource is returned to communicate with the client. If an error occurs, false is returned.
Example: <?php // Create socket server $server = stream_socket_server('tcp://127.0.0.1:8080', $errno, $errstr);
if (!$server) { echo "Cannot create socket server: $errstr ($errno)"; } else { echo "Waiting for client connection...\n";
// 接受客户端连接$client = stream_socket_accept($server); if (!$client) { echo "无法接受客户端连接"; } else { // 与客户端通信$message = "欢迎连接到服务器"; fwrite($client, $message); // 读取客户端发送的数据$data = fread($client, 1024); echo "接收到客户端数据:$data"; // 关闭客户端连接fclose($client); } // 关闭服务器fclose($server);
} ?> In the above example, first use the stream_socket_server() function to create a socket server and bind it to the local port 8080. Then use the stream_socket_accept() function to wait for the client to connect and return a new socket resource for communication with the client. During communication with the client, use the fwrite() function to send a welcome message to the client, and use the fread() function to read the data sent by the client. Finally, use the fclose() function to close the client connection and the server connection.