java 输入流冻结

发布于 2024-09-16 11:22:35 字数 334 浏览 2 评论 0原文

我试图运行一个进入套接字的线程,抓取输入流并读取它。我创建了数百个这样的线程,并设置了读取超时,但线程仍然停留在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一梦等七年七年为一梦 2024-09-23 11:22:35

奇怪的代码。您创建一个缓冲区,将一个字节读入其中,然后解析该字节,然后重复整个过程。一个字节肯定不需要太多解析。您永远不会从读取中检查 -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.

等数载,海棠开 2024-09-23 11:22:35

调用 skt.available(),然后调用 read 多次,或者使用 skt.read(byte[])。否则 skt.read() 将阻塞。您设置的超时是连接到套接字的超时,而不是读取超时。

Call skt.available(), and then call read that many times, or use skt.read(byte[]). Other wise skt.read() will block. The timeout your setting is to connect to the socket, and not a read timeout.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文