Java输入流缓冲对象?

发布于 2024-11-05 11:25:14 字数 308 浏览 1 评论 0原文

我有一个客户端-服务器应用程序,每次有新的客户端套接字加入时,服务器都会向所有客户端发送所有客户端的列表。问题是,当新客户端加入时,它会获得正确的列表,但旧客户端会获得他们加入时获得的旧列表。 有点像他们每次从输入流中获取相同的对象。

我可以以某种方式刷新输入流吗?

读取对象:

while((inObject = in.readObject()) != null) {
   ...
}

发送对象:

out.writeObject(object);

I have a client-server application where the server sends all clients a list of all clients every time a new client socket joins. The problem is, that when a new client joins it gets the right list but the old clients get the old list they got when joining themselves.
Sort of like they take the same object from the input stream every time.

Can I somehow flush the input stream?

Reading the object:

while((inObject = in.readObject()) != null) {
   ...
}

Sending the object:

out.writeObject(object);

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

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

发布评论

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

评论(2

疯狂的代价 2024-11-12 11:25:14

ObjectOutputStream.reset( ) 就是您要寻找的内容。

它还可以防止您耗尽内存,否则可能会发生这种情况。原因是 ObjectInput/OutputStream 类缓存了通过它们发送的所有对象,这也防止了这些对象被垃圾收集。这对于处理循环引用是必要的,并且还可以提高多次发送对象时的性能。

ObjectOutputStream.reset() is what you're looking for.

It will also prevent you from running out of memory, which could otherwise happen. The reason is that the ObjectInput/OutputStream classes cache all objects that have been sent through them, which also prevents those objects from being garbage collected. This is necessary to deal with circular references, and also improves performance when objects are sent multiple times.

恋竹姑娘 2024-11-12 11:25:14

我怀疑问题在于您正在修改现有对象,然后重用现有的ObjectOutputStream。对 ObjectOutputStream 调用 reset 可有效清除其对可能修改的对象的引用的缓存。

I suspect the problem is that you're modifying existing objects, then reusing the existing ObjectOutputStream. Call reset on the ObjectOutputStream to effectively clear its cache of references to potentially-modified objects.

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