在服务器 - 客户端应用程序中使用ObjectInputStream的ClassCastException

时间:2016-04-29 15:42:45

标签: java sockets client-server classcastexception objectinputstream

我正在尝试通过套接字发送对象,但是当我想在客户端中读取对象时,我得到了java.lang.ClassCastException。

我的对象是以下内容,我在两个项目(服务器和客户端)中都有它。

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;
    }
}

发送部分:

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

接收方部分:

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

错误信息:

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

我用同样的结果尝试了一切。 我找不到我的错误。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您需要在两个Data类中添加相同的SerializableID,请查看:this