4

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);
2
  • The clients are getting what you're sending them. They aren't "taking the same object from the input stream". You need to fix however it is that you're sending the list because you're not sending the right data. Commented May 8, 2011 at 19:08
  • 1
    ObjectOutputStream.reset() is the answer as below here, but BTW your loop termination condition is probably wrong. ObjectInputStream.readObject() only returns null if you wrote a null. At EOS it throws an EOFException. Commented May 9, 2011 at 1:36

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.