C#實現(xiàn)UDP通信方式
更新時間:2025年01月07日 16:47:12 作者:一介學徒
文章介紹了如何使用C#實現(xiàn)UDP通信,包括UDP服務(wù)器和客戶端的實現(xiàn)步驟和示例代碼,服務(wù)器關(guān)鍵類為UdpClient和IPEndPoint,實例化對象后可以通過異步任務(wù)發(fā)送數(shù)據(jù)并接收數(shù)據(jù),客戶端同樣使用UdpClient和IPEndPoint,連接到遠程服務(wù)器后開新任務(wù)接收數(shù)據(jù)
C#實現(xiàn)UDP通信
一、UDP服務(wù)器
- 1、關(guān)鍵類: UdpClient、IPEndPoint;
- 2、實例化一個UdpClient對象;
- 3、使用IPEndPoint建立與遠程對象的連接;
- 4、開一個異步新任務(wù)發(fā)送數(shù)據(jù);
- 5、主進程接收數(shù)據(jù);
示例代碼:
public static void Main() { UdpClient client = new UdpClient(8889); CancellationTokenSource cts = new CancellationTokenSource(); IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0); Task.Factory.StartNew(() => { while (!cts.IsCancellationRequested) { string? sendMessage = Console.ReadLine(); if (sendMessage != null) { byte[] data = Encoding.Default.GetBytes(sendMessage); client.Send(data, remotePoint); } } }, cts.Token); while (true) { byte[] recvdata = client.Receive(ref remotePoint); if (recvdata != null) { string recvMessage = Encoding.UTF8.GetString(recvdata); if (recvMessage == "quit") { cts.Cancel(); client.Close(); return; } StringBuilder sb = new StringBuilder("客戶端:"); sb.Append(recvMessage); Console.WriteLine(sb); } } }
二、UDP客戶端
- 1、關(guān)鍵類: UdpClient、IPEndPoint;
- 2、實例化一個UdpClient對象;
- 3、使用IPEndPoint建立與遠程服務(wù)器的連接;
- 4、開新任務(wù)接收數(shù)據(jù);
- 5、主進程發(fā)送數(shù)據(jù);
示例代碼:
public static void Main() { UdpClient client = new UdpClient(8888); IPAddress remoteIp = IPAddress.Parse("127.0.0.1"); int remotePort = 8889; IPEndPoint? remoteEndPoint = new IPEndPoint(remoteIp, remotePort); CancellationTokenSource cts = new CancellationTokenSource(); Task.Factory.StartNew(() => { while (!cts.IsCancellationRequested) { try { byte[] data = client.Receive(ref remoteEndPoint); if (data != null) { StringBuilder sb = new StringBuilder("服務(wù)器:"); sb.Append(Encoding.UTF8.GetString(data)); Console.WriteLine(sb); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); break ; } } }, cts.Token); while (true) { string? sendMessage = Console.ReadLine(); if (sendMessage != null) { byte[] data = Encoding.Default.GetBytes(sendMessage); client.Send(data, remoteEndPoint); if (sendMessage == "quit") { cts.Cancel(); client.Close(); return; } } } }
三、最終效果
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C# 委托的三種調(diào)用示例(同步調(diào)用 異步調(diào)用 異步回調(diào))
本文將主要通過同步調(diào)用、異步調(diào)用、異步回調(diào)三個示例來講解在用委托執(zhí)行同一個加法類的時候的的區(qū)別和利弊2013-12-12C#?使用SpecFlow創(chuàng)建BDD測試用例的示例代碼
這篇文章主要介紹了C#?使用SpecFlow創(chuàng)建BDD測試用例,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06關(guān)于C#泛型列表List<T>的基本用法總結(jié)
本篇文章主要是對C#中泛型列表List<T>的基本用法進行了詳細的總結(jié)介紹,需要的朋友可以過來參考下,希望對大家有所幫助2014-01-01C# 使用Microsoft Edge WebView2的相關(guān)總結(jié)
這篇文章主要介紹了C# 使用Microsoft Edge WebView2的相關(guān)總結(jié),幫助大家更好的理解和學習使用c#,感興趣的朋友可以了解下2021-02-02