Socket s = new Socket(server, port); System.out.println(s.getSoTimeout()); s.setSoTimeout(5000); InputStream in = s.getInputStream(); 现在我们尝试从这个socket中读数据。如果超过了指定的时间还读不到任何数据,程序将抛出一个java.io.InterruptedIOException。你可以捕获这一违例并决定是否尝试进行另一次读取操作:
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"); // 决定是否继续读取 } 在早于1.4的Java版本中,当从socket中读取数据时,你的程序不得不阻塞起来,但并不意味着你的程序这时什么也不能做。