java - 关闭输出流时 Java 套接字的行为

标签 java sockets

有人可以解释 Java 套接字中的以下行为吗:

大致思路是这样的:

  1. 打开socket,获取I/O流。
  2. 写入请求,关闭流
  3. 读取响应,在流中关闭
  4. 关闭套接字。

这是我的问题/问题。

如果我使用一个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/

相关文章:

java - orderBy 在集合字段上的用途?

在 C 中的 UDP 客户端服务器中每秒计算吞吐量

python - 如何以智能方式将UDP客户端消息发送到UDP服务器解析消息

java - 带数据包的套接字?我应该用什么?

c - 将相同的套接字 fd 两次添加到 fd_set 然后调用 select

java - 如何在 Seam 2 中实现 resourcebundle (messages.properties) 的热重载

java - 对无限制的 Java 驻留集大小 (RSS) 增长进行故障排除

java - 通过 FileSystem 对象从文件系统读取

java excel 到 csv 文件转换

c - strtol() 错误地返回 0