Java - 从输入流读取时卡住

发布于 2025-01-02 08:36:58 字数 464 浏览 1 评论 0原文

您好,我目前正在使用套接字和输入/输出流。我用来发送字节的循环有一个奇怪的问题。由于某种原因,当它试图从输入流中读取数据时,它会被卡住,而它应该停止。有谁知道出了什么问题吗?

     int bit;
     final byte[] request = new byte[1024];

     if (response instanceof InputStream)
     {   
         while ((bit = response.read(request)) > 0) { // <-- Stuck here
             incoming.getOutputStream().write(request,0,bit);
             incoming.getOutputStream().flush();
         }
     }   
     incoming.close();

Hello I am currently working with sockets and input/output streams. I have a strange problem with my loop I use to send bytes. For some reason it get stuck when it tries to read from the inputstream when it is supposed to stop. Does anyone have any idea whats wrong?

     int bit;
     final byte[] request = new byte[1024];

     if (response instanceof InputStream)
     {   
         while ((bit = response.read(request)) > 0) { // <-- Stuck here
             incoming.getOutputStream().write(request,0,bit);
             incoming.getOutputStream().flush();
         }
     }   
     incoming.close();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

淡笑忘祈一世凡恋 2025-01-09 08:36:58

InputStream.read 会阻塞,直到输入数据可用、检测到文件结尾或引发异常。

您不会捕获异常,也不检查 EOF。

InputStream.read blocks until input data is available, end of file is detected, or an exception is thrown.

You don't catch the exception, and don't check for EOF.

入怼 2025-01-09 08:36:58

我过去所做的让每一侧保持开放的做法是在每条消息的末尾添加一个您不会期望在消息中看到的终止字符。如果您自己构建消息,那么您可以使用诸如 ; 之类的字符,或者可能是双管道或 || 之类的字符。然后只需在接收端检查该字符即可。只是一个解决方法。不是解决方案。这对我来说是必要的,但可能不适合你。

What I've done in the past to leave each side open is to add a termination character to the end of each message that you wouldn't expect to see in the message. If you are building the messages yourself then you could use a character such as a ; or maybe double pipes or something ||. Then just check for that character on the receiving end. Just a workaround. Not a solution. It was necessary in my case but may not be for you.

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