关闭输出流时Socket的行为(stackoverflow)
来源:互联网 发布:数据库的储存过程 编辑:程序博客网 时间:2024/06/08 17:45
stackoverflow上的一个提问,直接拿过来了,英语应该都能看懂。
Can someone explain the following behavior in Java sockets:
The general idea is this:
- Open socket, Obtain I/O streams.
- Write request, Close out stream
- Read Response, Close in stream
- 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.
- 关闭输出流时Socket的行为(stackoverflow)
- 输出流关闭造成的Socket关闭
- Java socket中关闭IO流后,发生什么事?(以关闭输出流为例)
- Java socket中关闭IO流后,发生什么事?(以关闭输出流为例)
- Java socket中关闭IO流后,发生什么事?(以关闭输出流为例)
- 小技巧: 当ACE_Svc_Handler关闭时使用的默认行为
- java socket 以及 流 关闭的问题
- socket 的关闭
- 如何优雅的关闭socket
- 关于socket 关闭的问题
- socket输入输出的关闭方式
- 线程关闭socket的方法
- C# Socket的安全关闭
- 【Stackoverflow好问题】重写(Override)equlas和hashCode方法时应考虑的问题
- 中国的stackoverflow
- StackOverFlow提问的艺术
- 输入流 inputStream close()后,它所在的Socket也将关闭
- 【android学习】socket传输中,流的关闭
- 【编程练习】收集的一些c++代码片,算法排序,读文件,写日志,快速求积分等等
- hdu 5093 Battle ships(二分图匹配)
- hdu4674 Trip Advisor,双连通分量,LCA
- eclipse远程调试jetty
- 【iOS7的一些总结】14、Block的概念和应用
- 关闭输出流时Socket的行为(stackoverflow)
- QQ通信协议_概述
- lua基础【三】唯一数据结构table表
- HDU - 2197 本原串
- 奇偶数分离
- 算法分析与设计的读书笔记加个人总结
- 回调函数的小结
- 11.6 如果iOS中xib 和viewcontroller 不对应
- 第十一周项目6-回文,素数-1