有人可以解释 Java 套接字中的以下行为吗:
大致思路是这样的:
- 打开socket,获取I/O流。
- 写入请求,关闭流
- 读取响应,在流中关闭
- 关闭套接字。
这是我的问题/问题。
如果我使用一个PrintWriter
进行输出,然后关闭它,它会关闭整个socket,后续的读取操作就惨败了。
如果我直接使用套接字的 shutdownOutput()
方法,它会正确关闭输出流 channel ,同时保持套接字处于 Activity 状态。
为什么关闭 PrintWriter
对象会同时关闭整个套接字?
最佳答案
这可能是您的代码的样子:
Socket socket;
PrintWriter pw = new PrintWriter(socket.getOutputStream());
pw.close();
现在,我们来看看Socket的getOutputStream()
方法的描述。
getOutputStream
public OutputStream getOutputStream() throws IOException
Returns an output stream for this socket. If this socket has an associated channel then the resulting output stream delegates all of its operations to the channel. If the channel is in non-blocking mode then the output stream's write operations will throw an
IllegalBlockingModeException
.Closing the returned
OutputStream
will close the associated socket.Returns:
an output stream for writing bytes to this socket.
Throws:
IOException - if an I/O error occurs when creating the output stream or if the socket is not connected.
从上面的描述,我们知道关闭返回的OutputStream
会关闭关联的socket。
现在,当您关闭 PrintWriter
时,它会关闭关联的 OutputStream
,这将关闭关联的套接字。
关于java - 关闭输出流时 Java 套接字的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8890303/