Java – ObjectInputStream – How do I wait for new data?

ObjectInputStream – How do I wait for new data?… here is a solution to the problem.

ObjectInputStream – How do I wait for new data?

I’m making a client-server application but I’m having some trouble reading objects on the server.

After my server connects to the client socket, I build the object input and output streams and pass them to my service() methods. There, I should be dealing with different types of messages from the client. It would be nice that I could get a message from the client (i.e. the object I designed Message ). But of course, what I want to do is have a loop so I can get the message, process it, and reply.

So far, my code only works for a single message. What happens with each iteration when I add my loop, my server just reads the same message over and over again before my client has a chance to send a new message over the socket (I think that’s what’s happening, at least).

So what I really need to do is figure out how to make my service() method wait for new input. Any ideas? Or am I close to this error? Do I need to create a new OIS on each iteration or…? Some code:

public void service(ObjectInputStream input, ObjectOutputStream output) throws IOException, Exception {

    _shouldService = true;

    while (_shouldService) {
                    // It just keeps reading the same message over and over
                    // I need it to wait here until the client sends a new message
                    // Unless I'm just approaching this all wrong!
        NetworkMessage message = (NetworkMessage) input.readObject();

        NetworkMessageHeader header = message.getHeader();

        String headerType = header.getType();

        if (headerType.equals(NetworkMessageHeader.NetworkMessageHeaderTypeConnect)) {
            doLoginForMessage(message, output);
        } else if (headerType.equals(NetworkMessageHeader.NetworkMessageHeaderTypeFiles)) {
            doFilesList(message, output);
        } else {
            System.out.println("Unrecognized header type: " + headerType);

        }
    }
}

Best Solution

The ObjectOutputStream cached object represents and does not detect if you resend the same instance from the client over and over again, but there are changes in it. If this is your case, you need to call resetthe stream before each send.

NetworkMessage message = new NetworkMessage();
for(;;) {
  message.setProperty(whatever);
  oos.reset();
  oos.writeObject(message);
}

Related Problems and Solutions