I am trying to send a serialized Java object from a client to a server via socket, but there is a cast error on the server side and I can’t figure out why.
The Class being serialized is below. (I am using Eclipse, and this class is in both the client
package and the server package.)
package client; //it is "package server;" on server side
import java.io.Serializable;
public class Simple implements Serializable {
public String msg;
public Simple(){
msg = "simple";
}
}
on client side, I did:
Simple obj = new Simple();
Socket socket = new Socket(hostname, portNum);
ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream());
objOut.writeObject(obj);
objOut.flush();
objOut.close();
on the server side, I did:
//already accepted clientSocket
ObjectInputStream objIn = new ObjectInputStream(clientSocket.getInputStream());
Simple anObj = (Simple) objIn.readObject();
System.out.println("from server: " + anObj.msg);
objIn.close();
clientSocket.close();
However, I got the error:
Exception in thread "main" java.lang.ClassCastException: client.Simple cannot be cast to server.Simple at server.Server.main
I tried something similar with the Server and Client in a single package, and both the serialization and inflation worked. I would really appreciate it if you can help me find out why it doesn’t work here.
Simply put; to avoid two types in different namespaces from colliding, the package name is a part of the type name.
What happens is that the client serializes a
client.Simple, which the server also deserializes as aclient.Simple. Then you proceed by casting it to aserver.Simple, which is an entirely different type.It can be shown by doing;
The code shows that the server knows that the type of the deserialized object is
client.Simple, and it simply can’t cast it to the separate typeserver.Simple.