关闭套接字的输入流是否也会关闭套接字连接?

2022-09-01 10:50:34

在 Java API 中,


Socket socket = serverSocket.accept();
BufferedReader fromSocket = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter toSocket = new PrintWriter(socket.getOutputStream());
//do sth with fromSocket ... and close it
fromSocket.close();
//then write to socket again
toSocket.print("is socket connection still available?\r\n");
//close socket
socket.close();

在上面的代码中,在我关闭 InputStream fromSocket 之后,套接字连接似乎不再可用 - 客户端不会收到“套接字连接仍然可用”消息。这是否意味着关闭套接字的输入流也会关闭套接字本身?


答案 1

是的,关闭输入流将关闭套接字。您需要在套接字上使用 shutdownInput 方法,以仅关闭输入流

//do sth with fromSocket ... and close it 
socket.shutdownInput(); 

然后,您仍然可以发送到输出插座

//then write to socket again 
toSocket.print("is socket connection still available?\r\n"); 
//close socket 
socket.close(); 

答案 2

推荐