1

I'm trying to send an object trough sockets, but when I want to read the object in the client I got java.lang.ClassCastException.

My object is the following and I have it in both projects(Server and Client).

class Data implements Serializable{

    int height;
    int width;
    int max;
    int zoom;
    int start;
    int end;
    int xMove;
    int yMove;

    public Data(int height, int width, int max, int zoom, int start, int end, int xMove, int yMove){
        this.height = height;
        this.width = width;
        this.max = max;
        this.zoom = zoom;
        this.start = start;
        this.end = end;
        this.xMove = xMove;
        this.yMove = yMove;
    }
}

The sending part:

try{
    Data dataToSend = new Data(height, width, max, zoom, start, end, xMove, yMove);
    out.writeObject(dataToSend);
}

The receiver part:

try{
    InputStream is = socket.getInputStream();
    Data dataToRead = (Data)ois.readObject();
}

And the error message:

java.lang.ClassCastException: lab05_server.Data cannot be cast to lab05_kliens.Data

I tried everything with the same result. I can't find my mistake.

Thank you for any help.

1 Answer 1

0

You need to have the same SerializableID added to both Data classes, take a look at :this

Sign up to request clarification or add additional context in comments.

5 Comments

I declared this in both files: private static final long serialVersionUID = 1L; and now I got the following error: Error0 :java.io.InvalidClassException: lab05_server.Data; local class incompatible: stream classdesc serialVersionUID = 1, local class serialVersionUID = -5600343588571323555
One class is correct as it is showing the ID as what you declared it : "1", the other is still picking up the default ID: "-5600343588571323555"
Yepp, I found the bug, in the client in the (Datas)ois.readObject(); part the Data's constructor isn't executed(I put there a test ouptup). How can I make the casting to work? Thank you.
The main take away from the link is the part that says "The two classes need to have the same package".
Thank you for help, unfortunately I need the two different packages because of the server-client structure, so I will remain at passing strings. Anyhow, thank you for helping me out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.