Person类:
package com.zhyea.olproxy.socket; import java.io.Serializable; public class Person implements Serializable { private static final long serialVersionUID = 3199890860738953693L; /** * 姓名 */ private String name; /** * 年龄 */ private int age; public Person(String name, int age){ this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
服务端:
package com.zhyea.olproxy.socket; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; public class Server { public static ArrayList<Socket> socketList = new ArrayList<Socket>(); public static void main(String[] args){ try { //创建一个ServerSocket,用以监听客户端Socket的请求 ServerSocket serverSocket = new ServerSocket(49000); while(true){ //接收到客户端的请求后,服务器端也产生一个socket Socket socket = serverSocket.accept(); ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); Person person = new Person("Robin", 16); oos.writeObject(person); //关闭输出流,关闭socket oos.close(); socket.close(); } } catch (IOException e) { e.printStackTrace(); } } }
客户端:
package com.zhyea.olproxy.socket; import java.io.ObjectInputStream; import java.net.Socket; public class Client { public static void main(String[] args){ try { Socket socket = new Socket("127.0.0.1", 49000); ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); Person robin = (Person)ois.readObject(); if(null!=robin)System.out.println(robin.getName() + "##" + robin.getAge()); ois.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); } } }
有两点需要注意
- 对象类需要实现Serializable接口;
- 通信流使用ObjectOutputStream 和ObjectInputStream 来处理。