示例目的:使用控制台項目模板分別新建一個服務器和一個客戶端,實現兩兩通訊
1. 新建服務器
1 static UdpClient udpServer; 2 static void Main(string[] args) 3 { 4 udpServer = new UdpClient(61000); // 當前服務器使用的端口 5 udpServer.Connect("127.0.0.1", 50000); // 與客戶端建立連接 6 Console.WriteLine("服務端已經開啟......"); 7 8 #region 開啟線程保持通訊 9 10 var t1 = new Thread(ReciveMsg); 11 t1.Start(); 12 var t2 = new Thread(SendMsg); 13 t2.Start(); 14 15 #endregion 16 } 17 18 /// <summary> 19 /// 接收消息 20 /// </summary> 21 static void ReciveMsg() 22 { 23 24 var remoteIpEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 50000); // 遠程端點,即發送消息方的端點 25 while (true) 26 { 27 byte[] receiveBytes = udpServer.Receive(ref remoteIpEndPoint); // 接收消息,得到數據報 28 string returnData = Encoding.UTF8.GetString(receiveBytes); // 解析字節數組,得到原消息 29 Console.WriteLine($"{remoteIpEndPoint.Address}:{remoteIpEndPoint.Port}," + returnData.ToString()); 30 } 31 32 } 33 34 /// <summary> 35 /// 發送消息 36 /// </summary> 37 static void SendMsg() 38 { 39 while (true) 40 { 41 var msg = Console.ReadLine().ToString(); // 獲取控制台字符串 42 byte[] sendBytes = Encoding.UTF8.GetBytes(msg); // 將消息編碼成字符串數組 43 udpServer.Send(sendBytes, sendBytes.Length); // 發送數據報 44 } 45 }
2. 新建客戶端
static UdpClient udpClient; static void Main(string[] args) { udpClient = new UdpClient(50000); // 當前客戶端使用的端口 udpClient.Connect("127.0.0.1", 61000); // 與服務器建立連接 Console.WriteLine("客戶端已啟用......"); #region 開啟線程保持通訊 var t1 = new Thread(SendMsg); t1.Start(); var t2 = new Thread(ReciveMsg); t2.Start(); #endregion } /// <summary> /// 發送消息 /// </summary> static void SendMsg() { while (true) { var msg = Console.ReadLine().ToString(); // 獲取控制台字符串 byte[] sendBytes = Encoding.UTF8.GetBytes(msg); // 將消息編碼成字符串數組 udpClient.Send(sendBytes, sendBytes.Length); // 發送數據報 } } /// <summary> /// 接收消息 /// </summary> static void ReciveMsg() { var remoteIpEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 61000); // 遠程端點,即發送消息方的端點 while (true) { byte[] receiveBytes = udpClient.Receive(ref remoteIpEndPoint); // 接收消息,得到數據報 string returnData = Encoding.UTF8.GetString(receiveBytes); // 解析字節數組,得到原消息 Console.WriteLine($"{remoteIpEndPoint.Address}:{remoteIpEndPoint.Port}," + returnData.ToString()); } }
3. 啟動服務器和客戶端,查看效果
不足之處還請指點