// 伺服器同一時間只能處理一個客戶端資料,下一個客戶端要處理必須等待第一個客戶端完成才能夠傳送資料

// 伺服器程式碼----------------------------------------------------------------------------------------------------------------------

 
import java.io.DataInputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
 
public class Server {
 
    public Server() {
 
        try {
            ServerSocket ss = new ServerSocket(1024);
            System.out.println("伺服器啟動於 : " + InetAddress.getLocalHost().getHostAddress() 
                                                                  + ":" + ss.getLocalPort());
 
            while (true) {
                Socket s = ss.accept();
                DataInputStream in = new DataInputStream(s.getInputStream());
                String msg = in.readUTF();
                System.out.println("來自" + s.getInetAddress() + "接收到的訊息 : " + msg);
            }
        } catch (Exception e) {
        }
    }
 
    public static void main(String[] args) {
        new Server();
    }
}

// 客戶端程式碼-----------------------------------------------------------------------------------------------------------------------

 

 
import java.io.DataOutputStream;
import java.net.InetAddress;
import java.net.Socket;
 
public class Client {
 
    public Client() {
        try {
            Socket s = new Socket(InetAddress.getByName("125.230.210.246"), 1024);
            DataOutputStream out = new DataOutputStream(s.getOutputStream());   // 產生網路串流物件
            out.writeUTF("Hello 你好");                                         // 將資料寫入網路串流,並輸出到網路
            s.close();
        } catch (Exception e) {
        }
    }
 
    public static void main(String[] args) {
        new Client();
    }
}
arrow
arrow
    全站熱搜

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