BufferedInputStream 和阻塞
我正在使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用缓冲流从套接字读取通常是一个坏主意,正是因为这个原因:如果它没有看到足够的数据来填充其内部缓冲区(它将大于 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.为您的套接字指定 100 毫秒超时。 setSoTimeout
Specify 100ms timeout for your socket. setSoTimeout