Presents your JAVA E-NEWSLETTER for March 3, 2003 <-------------------------------------------> USE TIMEOUTS WHEN READING SOCKETS Although Java 1.4 introduced non-blocking I/O to the Java API, Java versions 1.3 and earlier don't support the feature. However, you can use the timeout property of the java.net.Socket class to get something like non-blocking I/O. To use the timeout property, you first create the socket, then set the timeout you want. The setSoTimeout method takes one parameter, an int that specifies the number of milliseconds the timeout socket should wait before throwing an exception, like this: Socket s = new Socket(server, port); System.out.println(s.getSoTimeout()); s.setSoTimeout(5000); InputStream in = s.getInputStream(); Now attempt to read from the socket. If no data can be read within the specified timeout, a java.io.InterruptedIOException will be thrown. You can catch the exception and decide whether to attempt another read: try { while ( (bytesRead = in.read(buffer)) != -1 ) { // do something with the data System.out.println(new String(buffer, 0, bytesRead)); } } catch (InterruptedIOException e) { System.err.print("timeout on read"); // decide whether to keep on reading or not } In Java versions prior to 1.4, your applications may have to block when reading from sockets, but they don't have to stand still. ----------------------------------------