Function name: stream_socket_shutdown()
Function description: stream_socket_shutdown() function closes socket connections created with stream_socket_client() or stream_socket_server().
Applicable version: PHP 4 >= 4.0.7, PHP 5, PHP 7
Syntax: bool stream_socket_shutdown(resource $stream, int $how)
parameter:
Return value: Return true on success, and false on failure.
Example:
// 创建套接字连接$socket = stream_socket_client('tcp://www.example.com:80', $errno, $errstr, 30); // 发送HTTP请求$request = "GET / HTTP/1.1\r\n"; $request .= "Host: www.example.com\r\n"; $request .= "Connection: close\r\n\r\n"; fwrite($socket, $request); // 关闭写入连接,继续读取服务器响应stream_socket_shutdown($socket, STREAM_SHUT_WR); // 读取服务器响应$response = ''; while (!feof($socket)) { $response .= fgets($socket); } // 关闭读取连接stream_socket_shutdown($socket, STREAM_SHUT_RD); // 关闭套接字连接fclose($socket);
The above example demonstrates how to use the stream_socket_shutdown() function to close the write connection after sending an HTTP request and continue reading the server's response. First, use the stream_socket_client() function to create a socket connection, then send an HTTP request and close the write connection. Next, use the fgets() function to loop through the server response until it ends. Finally, close the read connection and close the socket connection.
Note that the order of closing connections in the example is to close the write connection first and then close the read connection. This is because in an HTTP request, the client sends the request first and then waits for the server to respond. Therefore, we first close the write connection to inform the server that the request has been sent, and then continue to read the server's response.