BufferedInputStream 和阻塞

发布于 2024-12-01 09:58:26 字数 606 浏览 0 评论 0原文

我正在使用 BufferedInputStream 从套接字读取。 BufferedInputStream 的内容如下:

socketInput.read(replyBuffer, 0, 7);

它由 mySocket 实例化

socketInput = new BufferedInputStream(mySocket.getInputStream());

,定义为 private Socket mySocket;

mySocket 由以下实例化mySocket = new Socket(ipAddress, port);

我已验证 mySocket 已连接到我的设备。我可以将数据发送到我的设备;但是,由于未知原因,我没有从我的设备接收信息,但这不是问题所在。

我希望我的 BufferedInputStream 如果未读取任何数据,则在 100 毫秒后返回。可以设置 BufferedInputStream 来执行此操作吗?现在,它无限期地阻塞。

I am using a BufferedInputStream to read from a socket. The BufferedInputStream reads as follows:

socketInput.read(replyBuffer, 0, 7);

It is instantiated by

socketInput = new BufferedInputStream(mySocket.getInputStream());

mySocket is defined as private Socket mySocket;

mySocket is instantiated by mySocket = new Socket(ipAddress, port);

I have verified that mySocket is connected to my device. I can send data to my device; however, I am not receiving from my device for unknown reasons but that is not the problem.

I want my BufferedInputStream to return after say 100ms if it does not read any data. Can the BufferedInputStream be setup to do this? Right now, it blocks indefinitely.

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

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

发布评论

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

评论(2

人│生佛魔见 2024-12-08 09:58:26

使用缓冲流从套接字读取通常是一个坏主意,正是因为这个原因:如果它没有看到足够的数据来填充其内部缓冲区(它将大于 7 个字符!),它将永远等待没有办法让它超时。只需直接使用SocketInputStream,问题就消失了。

It's generally a bad idea to use a buffered stream for reading from a socket, for exactly this reason: it will wait forever if it doesn't see enough data to fill its internal buffer (which is going to be larger than 7 characters!) There's no way to make it time out. Just use the SocketInputStream directly, and the problem goes away.

小傻瓜 2024-12-08 09:58:26

为您的套接字指定 100 毫秒超时。 setSoTimeout

Specify 100ms timeout for your socket. setSoTimeout

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