首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

请教socket中read()<0表示流结束么

2013-10-06 
请问socket中read()0表示流结束么?看到一段两个socket之间传递数据的代码:void pipe(InputStream is0, In

请问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。最好都捕获掉。

热点排行