C#中使用UDP通信的示例
網(wǎng)絡(luò)通信協(xié)議中的UDP通信是無連接通信,客戶端在發(fā)送數(shù)據(jù)前無需與服務(wù)器端建立連接,即使服務(wù)器端不在線也可以發(fā)送,但是不能保證服務(wù)器端可以收到數(shù)據(jù)。本文實例即為基于C#實現(xiàn)的UDP通信。具體功能代碼如下:
服務(wù)器端代碼如下
static void Main(string[] args)
{
UdpClient client = null;
string receiveString = null;
byte[] receiveData = null;
//實例化一個遠程端點,IP和端口可以隨意指定,等調(diào)用client.Receive(ref remotePoint)時會將該端點改成真正發(fā)送端端點
IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
client = new UdpClient(11000);
receiveData = client.Receive(ref remotePoint);//接收數(shù)據(jù)
receiveString = Encoding.Default.GetString(receiveData);
Console.WriteLine(receiveString);
client.Close();//關(guān)閉連接
}
}
客戶端代碼如下:
static void Main(string[] args)
{
string sendString = null;//要發(fā)送的字符串
byte[] sendData = null;//要發(fā)送的字節(jié)數(shù)組
UdpClient client = null;
IPAddress remoteIP = IPAddress.Parse("127.0.0.1");
int remotePort = 11000;
IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);//實例化一個遠程端點
while (true)
{
sendString = Console.ReadLine();
sendData = Encoding.Default.GetBytes(sendString);
client = new UdpClient();
client.Send(sendData, sendData.Length, remotePoint);//將數(shù)據(jù)發(fā)送到遠程端點
client.Close();//關(guān)閉連接
}

以上就是C#中使用UDP通信的示例的詳細內(nèi)容,更多關(guān)于c# udp通信的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#如何Task執(zhí)行任務(wù),等待任務(wù)完成
這篇文章主要介紹了C#如何Task執(zhí)行任務(wù),等待任務(wù)完成,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06
C#三種判斷數(shù)據(jù)庫中取出的字段值是否為空(NULL) 的方法
最近操作數(shù)據(jù)庫,需要判斷返回的字段值是否為空,在網(wǎng)上收集了3種方法供大家參考2013-04-04
使用C# Winform應(yīng)用程序獲取網(wǎng)頁源文件的解決方法
本篇文章是對使用C# Winform應(yīng)用程序獲取網(wǎng)頁源文件的方法進行了詳細的分析介紹,需要的朋友參考下2013-05-05

