C#中使用UDP通信實(shí)例
更新時(shí)間:2014年08月15日 11:55:55 投稿:shichen2014
這篇文章主要介紹了C#中使用UDP通信實(shí)例,非常實(shí)用的技巧,需要的朋友可以參考下
網(wǎng)絡(luò)通信協(xié)議中的UDP通信是無連接通信,客戶端在發(fā)送數(shù)據(jù)前無需與服務(wù)器端建立連接,即使服務(wù)器端不在線也可以發(fā)送,但是不能保證服務(wù)器端可以收到數(shù)據(jù)。本文實(shí)例即為基于C#實(shí)現(xiàn)的UDP通信。具體功能代碼如下:
服務(wù)器端代碼如下:
static void Main(string[] args)
{
UdpClient client = null;
string receiveString = null;
byte[] receiveData = null;
//實(shí)例化一個(gè)遠(yuǎn)程端點(diǎn),IP和端口可以隨意指定,等調(diào)用client.Receive(ref remotePoint)時(shí)會將該端點(diǎn)改成真正發(fā)送端端點(diǎn)
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);//實(shí)例化一個(gè)遠(yuǎn)程端點(diǎn)
while (true)
{
sendString = Console.ReadLine();
sendData = Encoding.Default.GetBytes(sendString);
client = new UdpClient();
client.Send(sendData, sendData.Length, remotePoint);//將數(shù)據(jù)發(fā)送到遠(yuǎn)程端點(diǎn)
client.Close();//關(guān)閉連接
}
}
程序最終運(yùn)行效果如下:

相關(guān)文章
C#常用數(shù)據(jù)結(jié)構(gòu)和算法總結(jié)
這篇文章主要介紹了C#常用數(shù)據(jù)結(jié)構(gòu)和算法,這里我們總結(jié)了一些知識點(diǎn),可以幫助大家理解這些概念。2016-06-06
Unity使用物理引擎實(shí)現(xiàn)多旋翼無人機(jī)的模擬飛行
這篇文章主要介紹了Unity使用物理引擎實(shí)現(xiàn)多旋翼無人機(jī)的模擬飛行,包括了詳細(xì)的原理介紹和代碼實(shí)現(xiàn),對物理引擎感興趣的同學(xué),可以參考下2021-04-04

