Java 网络编程 之 传输对象Serialization 序列化

    技术2024-12-04  18

     

    package level.java.lang.transientnet;

    import java.io.Serializable;

    public class Dog implements Serializable{

    private static final long serialVersionUID = 7540895426148355331L;

    private transient String name;

    private int age;

    private float length;

    private float height;

    public Dog(String name,int age,float length,float height){

    this.name=name;

    this.age=age;

    this.length=length;

    this.height=height;

    }

    public String toString(){

    StringBuilder sb=new StringBuilder();

    sb.append("Name:").append(name).append("/t");

    sb.append("Age:").append(age).append("/t");

    sb.append("Length:").append(length).append("/t");

    sb.append("Height:").append(height).append("/t");

    return sb.toString();

    }

    }

     

     

     

    package level.java.lang.transientnet;

     

    import java.io.IOException;

    import java.io.InputStream;

    import java.io.ObjectInputStream;

    import java.net.ServerSocket;

    import java.net.Socket;

     

    public class Server {

    public static void listen() throws IOException, ClassNotFoundException{

    ServerSocket so=new ServerSocket(9000);

    Socket clSo=so.accept();

    InputStream input=clSo.getInputStream();

    ObjectInputStream objInput=new ObjectInputStream(input);

    Dog dog=(Dog) objInput.readObject();

    input.close();

    System.err.println(dog.toString());

    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {

    listen();

    }

     

    }

     

     

     

     

    package level.java.lang.transientnet;

     

    import java.io.IOException;

    import java.io.ObjectOutputStream;

    import java.io.OutputStream;

    import java.net.Socket;

    import java.net.UnknownHostException;

     

    public class Client {

     

    public static void send() throws UnknownHostException, IOException{

    Socket clSo=new Socket("127.0.0.1",9000);

    OutputStream out=clSo.getOutputStream();

    Dog d=new Dog("Jemy",23,50,23);

    ObjectOutputStream output=new ObjectOutputStream(out);

    output.writeObject(d);

    output.close();

     

     

    }

    public static void main(String[] args) throws UnknownHostException, IOException {

    send();

    }

     

    }

     

    最新回复(0)