简单的Client和Server的实现,传输对象流

(测试时,要先启动服务器端,再启动客户端,如果出现Connection reset的异常,说明Student类没有实现序列化。

为什么yaos要实现序列化呢?https://blog.csdn.net/thinkingcao/article/details/75133183

参考这篇博客)

Server服务器端

public class server {
	public static void main(String[] args) throws Exception {
		//1.创建服务器端套接字对象
		ServerSocket ss=new ServerSocket(10098);
		//2.创建兼听客户端socket
		Socket socket = ss.accept();
		//3.使用流接收
		InputStream is = socket.getInputStream();
		BufferedInputStream bis = new BufferedInputStream(is);
		ObjectInputStream ois = new ObjectInputStream(bis);
		System.out.println("我服务器端要开始接收了哈!");
		Student stu=(Student)ois.readObject();
		String string = stu.toString();
		System.out.println(socket.getInetAddress().getHostAddress()+":"+string);
		//4.关闭流
		socket.close();
		ss.close();
	}
}

Client客户端

public class client {
	public static void main(String[] args) throws Exception {
		Student stu=new Student();
		stu.setName("静静");
		stu.setWord("今天天气真好啊!");
		//1.创建客户端套接字对象
		Socket s=new Socket("127.0.0.1",10098);
		//2.使用流写
		OutputStream os = s.getOutputStream();
		BufferedOutputStream bos = new BufferedOutputStream(os);
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		System.out.println("客户端开始传输数据了!");
		oos.writeObject(stu);
		//3.关闭流
		oos.close();
		bos.close();
		os.close();
		s.close();
	}
}

Student实体类

//实体类要进行序列化
public class Student implements Serializable{
	private String name;
	private String word;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getWord() {
		return word;
	}
	public void setWord(String word) {
		this.word = word;
	}
	public Student(String name, String word) {
		super();
		this.name = name;
		this.word = word;
	}
	public Student() {
		super();
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", word=" + word + "]";
	}
}

 

你可能感兴趣的:(简单的Client和Server的实现,传输对象流)