当前位置:天才代写 > tutorial > JAVA 教程 > Java Socket输入流如何检测到EOF

Java Socket输入流如何检测到EOF

2017-11-02 08:00 星期四 所属: JAVA 教程 浏览:668

对付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 becausethe 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。

作者:csdn博客 kingspider-sh

 

    关键字:

天才代写-代写联系方式