[英]Behavior of Java sockets when closing output stream
Can someone explain the following behavior in Java sockets: 有人可以解释Java套接字中的以下行为:
The general idea is this: 一般的想法是这样的:
Here's my question / issue. 这是我的问题/问题。
If I use a PrintWriter
for output, and then close it, It closes the whole socket, and the subsequent read operation fails miserably. 如果我使用
PrintWriter
进行输出,然后关闭它,它会关闭整个套接字,后续的读操作会失败。
Instead if I directly use the socket's shutdownOutput()
method, it correctly closes the output stream channel, while keeping the socket alive. 相反,如果我直接使用套接字的
shutdownOutput()
方法,它会正确关闭输出流通道,同时保持套接字处于活动状态。
Why would closing the PrintWriter
object take the whole socket down with it? 为什么关闭
PrintWriter
对象会占用整个套接字?
This may be what your code looks like: 这可能是您的代码的样子:
Socket socket;
PrintWriter pw = new PrintWriter(socket.getOutputStream());
pw.close();
Now, let's have a look at the description of getOutputStream()
method of Socket. 现在,让我们看一下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
.如果通道处于非阻塞模式,则输出流的写操作将抛出
IllegalBlockingModeException
。Closing the returned
OutputStream
will close the associated socket.关闭返回的
OutputStream
将关闭关联的套接字。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.
IOException - 如果在创建输出流时发生I / O错误或者未连接套接字。
from the description above, we know closing the returned OutputStream
will close the associated socket. 从上面的描述中,我们知道关闭返回的
OutputStream
将关闭相关的套接字。
Now, when you close the PrintWriter
, it'll close the associated OutputStream
which will close the associated socket. 现在,当您关闭
PrintWriter
,它将关闭关闭的OutputStream
,它将关闭相关的套接字。
It is probably because calling the close()
method of PrintWriter
is tracing back through the hierarchy and calling the close()
method of the SocketOutputStream
as well. 这可能是因为调用
PrintWriter
的close()
方法正在追溯层次结构并调用SocketOutputStream
的close()
方法。 As part of the close()
method for the SocketOutputStream
it also calls the close()
method for the Socket
as well, which would in term close the SocketInputStream
as well. 作为
SocketOutputStream
的close()
方法的SocketOutputStream
它也为Socket
调用close()
方法,这也将关闭SocketInputStream
。 Calling the shutdownOutput()
function instead sends any previously written data followed by TCP's normal connection termination sequence. 调用
shutdownOutput()
函数会发送任何先前写入的数据,然后发送TCP的正常连接终止序列。 It then disables the output stream. 然后它禁用输出流。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.