java在Client和Servet端进行自定义对象传输时注意要点
- 必须在客户端和服务端各自创建一个被序列化的相同的类,类中的字段也必须相同,否则有些字段会访问不到
- 必须把这两个类分别放在客户端与服务端具有相同包名的包下面,否则出现ClassNotFoundException异常或者ClassCastException异常
- 如图
客户端代码:
package TCP;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import Public.Message;
public class client {
public static void main(String[] args ) throws Exception {
Socket socket = new Socket("127.0.0.1",9999);
ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream objIn = new ObjectInputStream(socket.getInputStream());
// objOut.writeObject("客户端来消息了");
Message message = new Message();
message.setAge(18);
objOut.writeObject(message);
}
}
服务端代码:
package webTest;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import Public.Message;
public class Server {
public static void main(String[] args) throws Exception {
ServerSocket ssocket = new ServerSocket(9999);
Socket socket = ssocket.accept();
ObjectInputStream objIn = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream());
objOut.writeObject("服务端来消息了");
Message message = new Message();
message = (Message) objIn.readObject();
System.out.println("message+"+message.getAge());
String str = (String)objIn.readObject();
System.out.println("str+"+str);
}
}
消息类:
package Public;
import java.io.Serializable;
public class Message implements Serializable{
/**
*
*/
private static final long serialVersionUID = 8625279621236358825L;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}