取消从 InputStream 读取

发布于 2024-08-12 12:04:10 字数 366 浏览 3 评论 0原文

目前我正在使用 ObjecInputStreamSocket 读取数据,使用这个简单的代码一切正常:

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 技术交流群。

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

发布评论

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

评论(3

相思故 2024-08-19 12:04:10

如果您有某种“主”线程,那么您应该对其执行 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.

亚希 2024-08-19 12:04:10

您可以使用 PushBackInputStream 来完成这个。读取一些字节后,您可以取消读取这些字节。

You can use a PushBackInputStream to accomplish this. After reading some bytes you can unread the bytes.

方圜几里 2024-08-19 12:04:10

查看 ObjectInputStream.markSupported() 返回的内容。如果返回true,您可以在开头调用ObjectInputStream.mark(),然后调用ObjectInputStream.reset()来倒回InputStream 返回到您标记的位置,以便稍后可以重用它。

See what ObjectInputStream.markSupported() returns. If it returns true, you can call ObjectInputStream.mark() at the beginning and then call ObjectInputStream.reset() to rewind the InputStream back to the place you marked so you can reuse it later.

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