Java输入流缓冲对象?
我有一个客户端-服务器应用程序,每次有新的客户端套接字加入时,服务器都会向所有客户端发送所有客户端的列表。问题是,当新客户端加入时,它会获得正确的列表,但旧客户端会获得他们加入时获得的旧列表。 有点像他们每次从输入流中获取相同的对象。
我可以以某种方式刷新输入流吗?
读取对象:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
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.
我怀疑问题在于您正在修改现有对象,然后重用现有的
ObjectOutputStream
。对ObjectOutputStream
调用reset
可有效清除其对可能修改的对象的引用的缓存。I suspect the problem is that you're modifying existing objects, then reusing the existing
ObjectOutputStream
. Callreset
on theObjectOutputStream
to effectively clear its cache of references to potentially-modified objects.