C#實現UDP通信方式
更新時間:2025年01月07日 16:47:12 作者:一介學徒
文章介紹了如何使用C#實現UDP通信,包括UDP服務器和客戶端的實現步驟和示例代碼,服務器關鍵類為UdpClient和IPEndPoint,實例化對象后可以通過異步任務發(fā)送數據并接收數據,客戶端同樣使用UdpClient和IPEndPoint,連接到遠程服務器后開新任務接收數據
C#實現UDP通信
一、UDP服務器
- 1、關鍵類: UdpClient、IPEndPoint;
- 2、實例化一個UdpClient對象;
- 3、使用IPEndPoint建立與遠程對象的連接;
- 4、開一個異步新任務發(fā)送數據;
- 5、主進程接收數據;
示例代碼:
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、關鍵類: UdpClient、IPEndPoint;
- 2、實例化一個UdpClient對象;
- 3、使用IPEndPoint建立與遠程服務器的連接;
- 4、開新任務接收數據;
- 5、主進程發(fā)送數據;
示例代碼:
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("服務器:");
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;
}
}
}
}三、最終效果

總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
C#?使用SpecFlow創(chuàng)建BDD測試用例的示例代碼
這篇文章主要介紹了C#?使用SpecFlow創(chuàng)建BDD測試用例,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06
C# 使用Microsoft Edge WebView2的相關總結
這篇文章主要介紹了C# 使用Microsoft Edge WebView2的相關總結,幫助大家更好的理解和學習使用c#,感興趣的朋友可以了解下2021-02-02

