取消从 InputStream 读取
目前我正在使用 ObjecInputStream
从 Socket
读取数据,使用这个简单的代码一切正常:
ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
Object response = input.readObject();
现在我想以某种方式取消读取,而不关闭流,所以我稍后可以再次阅读它。是否可以?
编辑:我想取消读取只是因为它阻塞了程序流程。我不需要重复阅读相同的信息。我只想取消它,以便我可以发送另一个请求,然后读取(另一个)响应。
Currently I am using an ObjecInputStream
to read from a Socket
, and everything works fine using this simple code:
ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
Object response = input.readObject();
Now I want to somehow cancel the read, without closing the stream, so that I can later read from it again. Is it possible?
Edit: I want to cancel the read just because it is blocking the program flow. I don't need to read the same information twice. I just want to cancel it so that I can send another request and then read the (another) response.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您有某种“主”线程,那么您应该对其执行 I/O。有一个线程专门用于读取和某些扩展处理输入。如果基于事件,则将结果排队到主线程;如果使用共享状态设计,则修改模型。
If you have some kind of "main" thread, then you should perform I/O off of it. Have a thread dedicated to reading and to some extends processing the input. Either queue the results to the main thread if event based, on modify the model if using a shared state design.
您可以使用 PushBackInputStream 来完成这个。读取一些字节后,您可以取消读取这些字节。
You can use a PushBackInputStream to accomplish this. After reading some bytes you can unread the bytes.
查看
ObjectInputStream.markSupported()
返回的内容。如果返回true
,您可以在开头调用ObjectInputStream.mark()
,然后调用ObjectInputStream.reset()
来倒回InputStream
返回到您标记的位置,以便稍后可以重用它。See what
ObjectInputStream.markSupported()
returns. If it returnstrue
, you can callObjectInputStream.mark()
at the beginning and then callObjectInputStream.reset()
to rewind theInputStream
back to the place you marked so you can reuse it later.