日期:2014-05-20  浏览次数:20836 次

socket 传输对象,出现ClassCastException
客户端的Message类
package com.client.comm;

import java.io.Serializable;
import java.net.Socket;
import java.util.ArrayList;

public class Message implements Serializable {

private ArrayList list;
//get和set方法
  ..........
}

服务器端的Message类
package com.server.comm;

import java.io.Serializable;
import java.net.Socket;
import java.util.ArrayList;

public class Message implements Serializable {

private ArrayList list;
  //get和set方法
.................
}


[color=#FF00FF]客户端代码(下面这段代码出错)[/color]
public class ClientThread implements Runnable {

// 定义主机地址
String host = "127.0.0.1";
// 定义端口号
int port = 2160;

Socket socket;
ObjectInputStream in;
ObjectOutputStream out;


ClientThread(Socket socket){
this.socket=socket;
try {
out = new ObjectOutputStream(socket.getOutputStream());
in = new ObjectInputStream(socket.getInputStream());

} catch (Exception e) {
e.printStackTrace();
}
}

  public void run() {
Message message = new Message();
while (true) {

if (socket.isClosed()) {
break;
}
try {
message = (Message) in.readObject();

} catch (Exception e) {
e.printStackTrace();
}
  }

}


java.lang.ClassCastException: com.server.comm.Message cannot be cast to com.client.comm.Message
at com.client.model.ClientThread.run(ClientThread.java:48)
at java.lang.Thread.run(Thread.java:619)

------解决方案--------------------
建一个Message类就好了。
------解决方案--------------------
Java code

package ClassSerializable;

public class TestCast {
    public static void main(String args[]){
        ClassSerializable.a.Message m1 = new ClassSerializable.a.Message();
        ClassSerializable.b.Message m2 =(ClassSerializable.b.Message)m1;//报错
    }
}

------解决方案--------------------
把Message放在同一个包下面试试