Search code examples
javaclientobjectinputstream

get the ObjectInputStream to see the different objects


I'm making a server-client application. There are two parts on my application a chat part and a game part. When I do the chatting I send String objects, when I play my game it sends Game objects to the other computer. How could I make my ObjectInputStream see the difference between the two kinds of object. I've been trying something like that:

if (input.readObject().getClass().isAssignableFrom(Game.class)){
                 game1 = (Game) input.readObject();
                  output.writeObject(game1);
                  output.flush();
             }else{
                 message = (String) input.readObject();
                 output.writeObject(message);
                 output.flush();
             }

it throws NotSerializableException when I'd like to use the game object, however the chatpart is working.


Solution

  • Does your Game object implement Serializable? It has to if you want to be able to read/write it using ObjectInputStream/ObjectOutputStream.

    Moreover, in addition to making Game serializable, the same applies to every field declared in the Game class. Each one must either implement Serializable or be declared as a transient (or static) member. If these conditions are not met, you will get a NotSerializableException when you try to write the object.

    Edit:

    There are some other issues in your code as well. For one thing, you are calling readObject() too many times. I'd suggest trying something like:

    Object next = input.readObject();
    if (next instanceof Game) {
        game1 = (Game)next;
        //...
    }
    else if (next instanceof String) {
        message = (String)next;
        //...
    }
    else {
        System.out.println("Unexpected object type:  " + next.getClass().getName());
    }