DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

使用输入流读取数据时的阻塞问题


使用java.io.BufferedInputStream.read(byte[])方法读取Socket中传过来的数据时,如果需要超时退出判断机制,一定要注意B ufferedInputStream.available()的使用。下面的代码片段是一个很标准的读取过程,其中第5行的判断很重要,因为read( byte[] )方法本身是阻塞的,如果自始至终is没有收到任何数据,就会一直阻塞在read()方法上(第6行),导致整个超时判断机制失去作用,而 available()方法的使用避免了这种可能性。

示例程序代码:

01      try {   02           long startTime = System.currentTimeMillis();   03           while (someCriteria) {   04                byte[] cache = new byte[1024];   05                if (is.available() > 0) {   06                     int count = is.read(cache);   07                     if (count <= 0) {   08                          if (System.currentTimeMillis() - startTime >= timeout) {   09                               throw new GapiException("Connection Time Out!");   10                          }   11                          continue;   12                     }   13                     // 后续处理   14                }   15                if (System.currentTimeMillis() - startTime >= timeout) {   16                     throw new GapiException("Connection Time Out!");   17                }   18                Thread.sleep(10);   19           }   20      } catch (Exception e) {   21           logger.error("ERROR: ", e);   22      }

程序流程图:



Published

Aug 20, 2010

Last Updated

Aug 20, 2010

Category

Tech

Tags

  • Java 106
  • read 1
  • Socket 4
  • 阻塞 2

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor