// 伺服器端程式碼 ----------------------------------------------------------------------------------------
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
 
public class UDPServer {
 
    public static void main(String[] args) throws Exception {
        byte[] buffer = new byte[65507];
        DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
        DatagramSocket ds = new DatagramSocket(80); // Set Server Port
        System.out.println("伺服器啟動於 : "
                + InetAddress.getLocalHost().getHostAddress() + ":" + ds.getLocalPort());
        String msg = "No Message...";
        while (true) {
            ds.receive(dp);
            msg = new String(dp.getData(), 0, dp.getLength());
            System.out.println("傳來的訊息 : " + msg);
        }
    }
}
 
// 客戶端程式碼 ------------------------------------------------------------------------------------------
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
 
public class UDPClient {
 
    public static void main(String[] args) throws Exception {
        DatagramPacket dp;
        Scanner s = new Scanner(System.in);
        System.out.println("請輸入要傳送的訊息 : ");
        String msg = "Key in";
        while (true) {
            msg = s.next();
            dp = new DatagramPacket(
                    msg.getBytes(), msg.getBytes().length, InetAddress.getByName("114.47.81.209"), 80);
            new DatagramSocket().send(dp);
        }
    }
}
 

    全站熱搜

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