java - TCP套接字中的IOException和EOFException有什么区别
问题描述
我是一个Java初学者,对Java socket编程不熟悉。我需要处理客户端断开连接的事件。我搜索了如何使用 Java 中的 read*、write* 函数检测套接字断开连接,有人说:
read() will return -1
readLine() returns null
readXXX() for any other X throws EOFException.
The only really reliable way to detect a lost TCP connection is to write to it. Eventually this will throw an IOException: connection reset, but it takes at least two writes due to buffering.
我不太确定 EOFException 是什么意思,以及 EOFException 和 IOException 之间有什么区别。官方手册上说EOFException“Signals that an end of file or end of stream has been reached unexpectedly during input.”,但我还是不明白在TCP socket连接中是什么。这是否意味着一个名为 close() 函数的 tcp 连接?什么原因会导致 tcp 连接出现 IOException?非常感谢。
解决方案
EOF Exception
是 的一个特例IO Exception
。(它是 IOException 的子类)。EOF 表示“文件结束”,EOF 异常表示文件结束(或您的情况下的任何流)已意外到达。这只是一种可能导致的情况IOException
。
在您的情况下,您的读取失败意味着连接已关闭。因此,由于连接出现问题,因此流已到达末尾。因此,请检查网络连接或另一端的套接字是否有问题。
这些答案也可能对您有所帮助。 https://stackoverflow.com/a/10724508/4848659
请参阅文档以了解 IOException 的整个子类为ChangedCharSetException, CharacterCodingException, CharConversionException, ClosedChannelException, EOFException, FileLockInterruptionException, FileNotFoundException, FilerException, FileSystemException, HttpRetryException, IIOException, InterruptedByTimeoutException,
...。
推荐阅读
- python - Tensorflow:了解LSTM模型的层结构
- java - maven 直接解析原生二进制文件
- python - 2类分类中的回归错误
- rest - 为什么要向 REST API 的响应添加链接?
- javascript - Firebase 断开连接
- c++ - 如何将像素缓冲区复制到更大的缓冲区
- swift - uicollectionview中的uiwebview得到白色的空白屏幕
- javascript - AngularJS ng-hide/show label/button if length(description) < 20
- server - 在命令行上运行“monit restart all”昨天还在工作
- mysql - SQL - 根据另一个列值设置列值