java 输入流冻结
我试图运行一个进入套接字的线程,抓取输入流并读取它。我创建了数百个这样的线程,并设置了读取超时,但线程仍然停留在 read() 行。
public void readPack() {
socket.setSoTimeout(4*1000);
if (socket.isConnected()) {
buffer parse = new buffer();
parse.addByte((byte) skt.getInputStream().read());
parseIncoming(parse);
}
} catch (Exception e) {}
}
Im trying to run a thread that goes to a socket, grabs the input stream, and reads it. Im creating hundreds of these threads and have set the timeout for reading and yet the thread still stays at the read() line.
public void readPack() {
socket.setSoTimeout(4*1000);
if (socket.isConnected()) {
buffer parse = new buffer();
parse.addByte((byte) skt.getInputStream().read());
parseIncoming(parse);
}
} catch (Exception e) {}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
奇怪的代码。您创建一个缓冲区,将一个字节读入其中,然后解析该字节,然后重复整个过程。一个字节肯定不需要太多解析。您永远不会从读取中检查 -1,因此当对等方断开连接时,此循环将无休止地旋转。最后 Socket.isConnected() 不是一个有用的测试,特别是它不会检测对等点断开连接。
Strange code. You create a buffer, read one byte into it, then parse that byte, then repeat the whole process. One byte surely doesn't take much parsing. You are never checking for -1 from the read so this loop will spin endlessly when the peer disconnects. And finally Socket.isConnected() isn't a useful test, and specifically it doesn't detect the peer disconnecting.
调用 skt.available(),然后调用 read 多次,或者使用 skt.read(byte[])。否则
skt.read()
将阻塞。您设置的超时是连接到套接字的超时,而不是读取超时。Call
skt.available()
, and then call read that many times, or useskt.read(byte[])
. Other wiseskt.read()
will block. The timeout your setting is to connect to the socket, and not a read timeout.