日期:2014-05-20  浏览次数:20808 次

请问socket中read()<0表示流结束么?
看到一段两个socket之间传递数据的代码:
void pipe(InputStream is0, InputStream is1, OutputStream os0,
OutputStream os1) throws IOException {
try {
int ir;
byte bytes[] = new byte[BUFSIZ];
while (true) {
try {
if ((ir = is0.read(bytes)) > 0) {
os0.write(bytes, 0, ir);
if (logging)
writeLog(bytes, 0, ir, true);
} else if (ir < 0)
break;
} catch (InterruptedIOException e) {
}
try {
if ((ir = is1.read(bytes)) > 0) {
os1.write(bytes, 0, ir);
if (logging)
writeLog(bytes, 0, ir, false);
} else if (ir < 0)

break;
} catch (InterruptedIOException e) {
}
}
} catch (Exception e0) {
System.out.println("Pipe异常: " + e0);
}
}


不明白为什么作者要加:InterruptedIOException,难道read()<0不表示流结束么?
java socket exception

------解决方案--------------------
InterruptedIOException 不是用来保证是否结束的而是 线程被打断的异常情况。
因为io可能会被阻塞。thread可以接收打断操作,打断阻塞的io,这个时候被阻塞的io会抛出InterruptedIOException 。

另外,确实有些时候io断开也会抛出其他异常ioexception。最好都捕获掉。