C#實(shí)現(xiàn)UDP通信方式
更新時(shí)間:2025年01月07日 16:47:12 作者:一介學(xué)徒
文章介紹了如何使用C#實(shí)現(xiàn)UDP通信,包括UDP服務(wù)器和客戶(hù)端的實(shí)現(xiàn)步驟和示例代碼,服務(wù)器關(guān)鍵類(lèi)為UdpClient和IPEndPoint,實(shí)例化對(duì)象后可以通過(guò)異步任務(wù)發(fā)送數(shù)據(jù)并接收數(shù)據(jù),客戶(hù)端同樣使用UdpClient和IPEndPoint,連接到遠(yuǎn)程服務(wù)器后開(kāi)新任務(wù)接收數(shù)據(jù)
C#實(shí)現(xiàn)UDP通信
一、UDP服務(wù)器
- 1、關(guān)鍵類(lèi): UdpClient、IPEndPoint;
- 2、實(shí)例化一個(gè)UdpClient對(duì)象;
- 3、使用IPEndPoint建立與遠(yuǎn)程對(duì)象的連接;
- 4、開(kāi)一個(gè)異步新任務(wù)發(fā)送數(shù)據(jù);
- 5、主進(jìn)程接收數(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("客戶(hù)端:");
sb.Append(recvMessage);
Console.WriteLine(sb);
}
}
}二、UDP客戶(hù)端
- 1、關(guān)鍵類(lèi): UdpClient、IPEndPoint;
- 2、實(shí)例化一個(gè)UdpClient對(duì)象;
- 3、使用IPEndPoint建立與遠(yuǎn)程服務(wù)器的連接;
- 4、開(kāi)新任務(wù)接收數(shù)據(jù);
- 5、主進(jìn)程發(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é)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
c# 解決IIS寫(xiě)Excel的權(quán)限問(wèn)題
使用以上方法必須對(duì)dcom進(jìn)行配置,給用戶(hù)使用office的權(quán)限2012-10-10
c#讀取圖像保存到數(shù)據(jù)庫(kù)中(數(shù)據(jù)庫(kù)保存圖片)
這篇文章主要介紹了使用c#讀取圖像保存到數(shù)據(jù)庫(kù)中的方法,大家參考使用吧2014-01-01
如何使用C#讀寫(xiě)鎖ReaderWriterLockSlim
這篇文章向大家介紹了讀寫(xiě)鎖ReaderWriterLockSlim,其優(yōu)點(diǎn)就是多個(gè)線(xiàn)程可以同時(shí)讀取該對(duì)象,要了解更多讀寫(xiě)鎖的知識(shí),仔細(xì)閱讀下文吧2015-07-07
Js中的substring,substr與C#中的Substring比較
本篇文章主要是對(duì)Js中的substring,substr與C#中的Substring進(jìn)行了比較。需要的朋友可以過(guò)來(lái)參考下,希望對(duì)大家有所幫助2014-01-01

