using System; using System.Net; using System.Net.Sockets; using System.Text; public class UdpClient { public static void Main(string[] args) // 主程式開始 { // 連接到 args[0] 參數所指定的 Server,使用連接埠 5555 IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(args[0]), 5555); // 建立 Socket,連接到 Internet (InterNetwork),使用 Udp 協定的 Datagram 方式 (Dgram)。 Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); while(true) // 不斷讀取鍵盤輸入,並傳送輸入訊息給伺服器。 { string input = Console.ReadLine(); // 讀取鍵盤輸入 if (input == "exit") // 如果輸入為 exit,則強制離開程式。 break; server.SendTo(Encoding.UTF8.GetBytes(input), ipep); // 將訊息以 UTF8 的方式編碼後傳出。 } Console.WriteLine("Stopping client"); // 印出 Stopping client 訊息。 server.Close(); // 關閉連線。 } }