使用tcp传递对象

客户端代码如下:

import java.net.*;
import java.io.*;

public class ObjectClient {

	public static void main(String[] args) {
		try {
			Socket s = new Socket("127.0.0.1", 8001); // 实际编程不要写死
			
			InputStream is = s.getInputStream();
			ObjectInputStream ois = new ObjectInputStream(is);
			
			Student stu = (Student)ois.readObject();
			
			System.out.println(stu);
			
			ois.close();
			s.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}


人服务器代码如下:

import java.net.*;
import java.io.*;

public class ObjectServer {
	public static void main(String[] args) {
		try {
			ServerSocket ss = new ServerSocket(8001);
			Socket s = ss.accept();
			
			OutputStream os = s.getOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(os);
			
			Student stu = new Student(1, "Ronnie", 37, "snooker");
			
			oos.writeObject(stu);
			
			oos.close();
			s.close();
			ss.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


要传递的对象类如下:

import java.io.Serializable;

public class Student implements Serializable {
	int id;
	String name;
	int age;
	String department;
	
	public Student(int id, String name, int age, String department) {
		this.id = id;
		this.name = name;
		this.age = age;
		this.department = department;
	}
	
	public String toString() {
		return id + ", " + name + ", " + age + ", " + department;
	}
}


注意:要传递的对象类必须实现Serializable接口

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值