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

时间:2010-10-18 01:56:31

标签: java api sockets

在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 个答案:

答案 0 :(得分:36)

是的,关闭输入流会关闭套接字。您需要在套接字上使用shutdownInput方法到close just the input stream

//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();