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.
Does your
Gameobject implementSerializable? It has to if you want to be able to read/write it usingObjectInputStream/ObjectOutputStream.Moreover, in addition to making
Gameserializable, the same applies to every field declared in theGameclass. Each one must either implementSerializableor be declared as atransient(orstatic) member. If these conditions are not met, you will get aNotSerializableExceptionwhen 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: