对象序列化在网络通信中的运用

来源:互联网 发布:战地2飞机数据修改 编辑:程序博客网 时间:2024/06/08 06:02
  1. 都知道对象序列化这个知识,可到底有什么用处?
    a当你想把的内存中的对象保存到一个文件中或者数据库中时候;
    b当你想用套接字在网络上传送对象的时候;
    c当你想通过RMI传输对象的时候
    2.今天通过实例来看看对象序列化在网络通信的运用(socket)
    3.对象继承序列化接口
import java.io.Serializable;public class TestObject implements Serializable{     /**      *      */     private static final long serialVersionUID = 1L;     private String name;     public String getName() {      return name;     }     public void setName(String name) {      this.name = name;     }    }

4.实现服务器端代码

package com;import java.net.ServerSocket;import java.net.Socket;public class SendServer extends java.lang.Thread { private boolean OutServer = false; private ServerSocket server; private final int ServerPort = 8765; public SendServer() {  try {   server = new ServerSocket(ServerPort);   System.out.println("The server is running...");  } catch (java.io.IOException e) {   System.out.println("Socket start-up error!");   System.out.println("IOException :" + e.toString());  } } public void run() {  Socket socket;  java.io.ObjectInputStream in;  while (!OutServer) {   socket = null;   try {    synchronized (server) {     socket = server.accept();    }    System.out.println("Built a connection: InetAddress = "      + socket.getInetAddress());    socket.setSoTimeout(15000);    in = new java.io.ObjectInputStream(socket.getInputStream());    TestObject data = (TestObject) in.readObject();    System.out.println("The value received:" + data.getName());    in.close();    in = null;    socket.close();   } catch (java.io.IOException e) {    System.out.println("Socket connection error!");    System.out.println("IOException :" + e.toString());   } catch (java.lang.ClassNotFoundException e) {    System.out.println("ClassNotFoundException :" + e.toString());   }  } } public static void main(String args[]) {  (new SendServer()).start(); }}

5.客户端代码

import java.io.ObjectOutputStream;import java.net.InetSocketAddress;import java.net.Socket;public class SendClient { private String address = "127.0.0.1"; private int port = 8765; public SendClient() {  // Prepare the data need to transmit  TestObject data = new TestObject();  data.setName("赵丽颖");     //给对象设置状态  Socket client = new Socket();  InetSocketAddress isa = new InetSocketAddress(this.address, this.port);  try {   client.connect(isa, 10000);   ObjectOutputStream out = new ObjectOutputStream(     client.getOutputStream());   // send object   out.writeObject(data);   //把序列化的数据写到输出流中   out.flush();   out.close();   out = null;   data = null;   client.close();   client = null;  } catch (java.io.IOException e) {   System.out.println("Socket connection error!");   System.out.println("IOException :" + e.toString());  } } public static void main(String args[]) {  new SendClient(); }} 

6.效果展示
这里写图片描述

0 0