首页 > 解决方案 > 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?非常感谢。

标签: java

解决方案


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,...。


推荐阅读