Java Socket输入流如何检测到EOF

对于InputStream的 read(b, off, len) 方法 public int read(byte[] b, int off, int len) throws IOException,Javadoc的说明为:

If len is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at end of file, the value -1 is returned; otherwise, at least one byte is read and stored into b.
The default implementation of this method blocks until the requested amount of input data len has been read, end of file is detected, or an exception is thrown.

那么对于服务端Socket的输入流来说,什么是 end of file - EOF?首先说明一点,没有所谓的标识字符是EOF,对于字节流来说,从0~255的每个字节都是正常的数据,EOF只是输入流的一种状态。

当Socket客户端关闭的时候,服务端输入流在读完所有数据之后就会检测到EOF,然后服务端输入流返回-1。如果客户端Socket没有关闭,并且没有数据可读取的情况下,read方法会阻塞,等待有数据可读。如果设置了SoTimeout,那么直到超时抛出异常,如果没有设置超时,那么会一直等待数据到达。
通过测试,客户端关闭Socket之后,服务端还可以重复读取,每次都返回-1。
原文地址:https://www.cnblogs.com/hainange/p/6153618.html