i have a weird problem. I am trying to write simple Client – Server app with chat option, but i ran into a problem – Object Input Stream reads wrong class. Error is:
Exception in thread "Thread-4" java.lang.ClassCastException: org.oxomoco.packets.PacketAlive cannot be cast to org.oxomoco.packets.PacketMessage
at org.oxomoco.server.SocketConnectionServer.run(SocketConnectionServer.java:52)
at java.lang.Thread.run(Unknown Source)
And it happens here:
PacketMessage pm = (PacketMessage)ois.readObject();
Which is in loop that looks like this:
while(true){
//if(ois.readObject() instanceof PacketMessage){
// pm = (PacketMessage)ois.readObject();
// se.println(ois.readObject().toString());
//}
if((ois.readObject() instanceof PacketMessage)==true){
System.out.println("It is: " + (ois.readObject() instanceof PacketMessage));
PacketMessage pm = (PacketMessage)ois.readObject();
se.acprintln(">>",uname + ": " +pm.getMsg());
}
if((ois.readObject() instanceof PacketAlive)==true){
System.out.println("-it is: " + (ois.readObject() instanceof PacketAlive));
PacketAlive pa = (PacketAlive)ois.readObject();
}
}
Somehow – even though i check instances – Object input stream is instance of PacketMessage when it should be instance of PacketAlive. Does anyone have an idea why, and of course – how to fix it?
You’re executing
several times, and getting a different object (of a different class?) each time.
readObject()pulls each object from the stream, rather than leave it there.Instead, read it, assign to a variable and then perform your tests etc. e.g.