Socket传输序列化对象

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Leo_eight/article/details/50322789


用Socket通信时, 有时传输序列化对象会带来很多方便.


如用户登录时, 把用户信息写入序列化对象里, 把该包含用户信息的序列化对象传输给客户端, 实现登录


代码如下:


序列化对象:

<span style="font-size:18px;color:#009900;">public class Customer implements Serializable{


	private static final long serialVersionUID = 1L;
	
	private String name;
	private String password;
	
	public void setName(String name){
		this.name = name;
	}
	
	public String getName(){
		return name;
	}
	
	public void setPassword(String password){
		this.password = password;
	}
	
	public String getPassword(){
		return password;
	}
}</span>


服务器端:

<span style="font-size:18px;color:#009900;">public class Server {
	
	public static void main(String[] args) {
		ServerSocket serverSocket = null;
		Socket socket = null;
		try {
		    serverSocket = new ServerSocket(30001);
			System.out.println("服务器启动..");
		        socket = serverSocket.accept();
			ObjectInputStream objIn = new ObjectInputStream(socket.getInputStream());
			Customer customer = (Customer)objIn.readObject();
			System.out.println("Name: " + customer.getName() + "\n" + 
					   "Password: " + customer.getPassword());
			objIn.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally{
			try {
				socket.close();
				serverSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
	}
}</span>

客户端:

<span style="font-size:18px;color:#009900;">public class Client {
	
	
	public static void main(String[] args) {
		String hostlocal = "192.168.1.200";
		int port = 30001;
		Socket socket = null;
		try {
			socket = new Socket(hostlocal, port);
			ObjectOutputStream objOut = new ObjectOutputStream(socket.getOutputStream());
			Customer customer = new Customer();
			customer.setName("Leo");
			customer.setPassword("123");
			objOut.writeObject(customer);
			objOut.flush();
			objOut.close();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {		
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}</span>



运行结果:




猜你喜欢

转载自blog.csdn.net/Leo_eight/article/details/50322789
今日推荐