我正在向服务器发送消息,该消息正确传递。
但是,当尝试读取结果时,我得到一个异常,提示 Socket 已关闭
。
知道如何关闭套接字的输出流,同时保持套接字和套接字的输入流打开以获得结果吗?
客户端代码:
Socket socket = new Socket("localhost", 9090);
String message = "Some message";
new OutputStreamWriter(socket.getOutputStream(), Charsets.UTF_8)
.append(message)
.close();
// The following line throws the exception when socket.getInputStream() is called:
String fromServer = CharStreams.toString(new InputStreamReader(socket.getInputStream(), Charsets.UTF_8));
异常(exception):
java.net.SocketException: Socket is closed
at java.net.Socket.getInputStream(Socket.java:903)
at alik.server.test.Client.pingServer(Client.java:24)
最佳答案
来自javadoc of Socket.getOutputStream()
:
Closing the returned
OutputStream
will close the associated socket.
换句话说,在完成输入流之前不要关闭输出流。关闭输入流也会关闭套接字(因此也会关闭输出流)。
你可以使用 Socket.shutdownOutput()
以防止进一步写入套接字,但我真的不明白使用它的意义,它可能导致对等方过早关闭其套接字,如 Stephen C在评论中解释:
The peer should only see the closed stream if it reads. What happens next will depend on how it responds to seeing the closed stream.
关于java - 如何在保持输入流打开以获得结果的同时关闭 Java 套接字输出流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51375999/