关闭输出流时Socket的行为(stackoverflow)

stackoverflow上的一个提问,直接拿过来了,英语应该都能看懂。

Can someone explain the following behavior in Java sockets:

The general idea is this:

  1. Open socket, Obtain I/O streams.
  2. Write request, Close out stream
  3. Read Response, Close in stream
  4. Close socket.

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.

Instead if I directly use the socket's shutdownOutput() method, it correctly closes the output stream channel, while keeping the socket alive.

Why would closing the PrintWriter object take the whole socket down with it?


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.

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.

from the description above, we know closing the returned OutputStream will close the associated socket.

Now, when you close the PrintWriter, it'll close the associated OutputStream which will close the associated socket.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值