Function name: socket_create_listen()
Applicable version: PHP 4 >= 4.1.0, PHP 5, PHP 7
Function description: The socket_create_listen() function creates a listening socket to accept incoming connection requests.
Syntax: resource socket_create_listen ( int $port [, int $backlog = 128] )
parameter:
Return value: Returns a listening socket resource when successful, and returns FALSE when failure.
Example:
$host = 'localhost'; $port = 8000; $socket = socket_create_listen($port); if ($socket === false) { echo "无法创建监听套接字: " . socket_strerror(socket_last_error()) . PHP_EOL; exit; } echo "正在监听{$host}:{$port}..." . PHP_EOL; while (true) { $clientSocket = socket_accept($socket); if ($clientSocket === false) { echo "无法接受连接请求: " . socket_strerror(socket_last_error($socket)) . PHP_EOL; break; } // 处理客户端请求... socket_close($clientSocket); } socket_close($socket);
In the above example, we create a listening socket and listen for connection requests on the specified port. Then, wait for the client's connection request by looping, and perform corresponding processing after receiving the connection. After processing is complete, close the client socket and continue listening for other connection requests. Finally, close the listening socket.