Function name: stream_socket_server()
Applicable version: PHP 4 >= 4.0.1, PHP 5, PHP 7
Function Description: The stream_socket_server() function creates a server socket resource and returns a stream resource that is used to listen for the specified local or remote address.
Syntax: resource stream_socket_server(string $local_socket, int &$errno = null, string &$errstr = null, int $flags = STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, resource $context = null)
parameter:
Return value: Returns a stream resource of a server socket resource when successful, and returns false when failure.
Example:
// 创建一个TCP 服务器套接字,并监听本地的8000端口$serverSocket = stream_socket_server("tcp://127.0.0.1:8000", $errno, $errstr); if (!$serverSocket) { die("创建服务器套接字失败:$errstr ($errno)"); } // 接受客户端连接并处理请求while ($clientSocket = stream_socket_accept($serverSocket)) { // 处理客户端请求// ... // 关闭客户端连接fclose($clientSocket); } // 关闭服务器套接字fclose($serverSocket);
In the example above, we use the stream_socket_server() function to create a TCP server socket and specify the 8000 port with the address 127.0.0.1 to listen. We then accept client connections using the stream_socket_accept() function and process client requests in a loop. Finally, close client connection and server sockets through the fclose() function.
Please note that the above example is just a simple example, and more complex processing logic and error handling may be required in practical applications.