Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObjectInputStream - How to wait for new data?

I've got a client-server app I'm making and I'm having a bit of trouble when reading objects on the server.

After my server connects to a client socket, I build object input and output streams and pass them along to my service() method. In there, I'm supposed to handle different kinds of messages from the client. I can get a message from the client (that is, a Message object, of my design) just fine. But of course, what I want to do is have a loop so I can get a message, process it, and respond back.

So far, my code only works for a single message. When I added my loop, what happened was on every iteration, my server just kept reading the same message over and over again before my client got a chance to send a new message over the socket (I think this is 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 approaching this wrong? Do I need to create a new OIS on every 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);

        }
    }
}
like image 847
jbrennan Avatar asked Nov 05 '22 05:11

jbrennan


1 Answers

The ObjectOutputStream caches object representations and will not detect if you are resending the same instance over and over again from the client side, but with changes in it. If this is your scenario you need to call reset on the stream before each send.

NetworkMessage message = new NetworkMessage();
for(;;) {
  message.setProperty(whatever);
  oos.reset();
  oos.writeObject(message);
}
like image 75
Perception Avatar answered Nov 09 '22 13:11

Perception