要被傳送的類別物件 MyClass : -------------------------------------------

import java.io.Serializable;
 
class MyClass implements Serializable {
 
    String s;
    int i;
    double d;
 
    public MyClass(String s, int i, double d) {
        this.s = s;
        this.i = i;
        this.d = d;
    }
 
    @Override
    public String toString() {
        return "s=" + s + ";   i=" + i + ";   d=" + d;
    }
}

客戶端類別 Client : -------------------------------------------

import java.io.BufferedOutputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
 
public class Client {
 
    public static void main(String[] args) throws Exception {
        Socket s = new Socket(InetAddress.getByName("127.0.0.1"), 1024);
 
        MyClass my = new MyClass("黃彥霖", 1234, 3.1415);
        System.out.println("原本物件:" + my);
        ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(s.getOutputStream()));
        oos.writeObject(my);
        oos.close();
    }
}
 
伺服器端類別 Server : -------------------------------------------
 
import java.io.BufferedInputStream;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
 
public class Server {
 
    public static void main(String[] args) throws Exception {
        ServerSocket ss = new ServerSocket(1024);
        System.out.println("等待連線...");
        Socket s = ss.accept();
 
        ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(s.getInputStream()));
        MyClass my = (MyClass) ois.readObject();
        System.out.println("物件還原後:" + my);
        ois.close();
    }
}
//----------------------------------------------------------------
 
Client 輸出結果 :
原本物件:s=黃彥霖;   i=1234;   d=3.1415
 
Server 輸出結果 :
等待連線...
物件還原後:s=黃彥霖; i=1234; d=3.1415
 
//----------------------------------------------------------------
arrow
arrow
    全站熱搜

    黃彥霖 發表在 痞客邦 留言(0) 人氣()