簡介
C#中的udp通信關鍵類:Udpclient,它位於命名空間System.Net.Sockets中,發送接收都是UdpClient類,
命名空間
using System.Net.Sockets;
using System.Net;
using System.Net.NetworkInformation;
using System.Management;
發送數據
1.Visual C# UdpClient類發送UDP數據包:
在具體使用中,一般分成二種情況:
(1).知道遠程計算機IP地址:
"Send"方法的調用語法如下:
參數說明:
dgram 要發送的 UDP 數據文報(以字節數組表示)。
bytes 數據文報中的字節數。
endPoint 一個 IPEndPoint,它表示要將數據文報發送到的主機和端口。
返回值 已發送的字節數。
下面使用UdpClient發送UDP數據包的具體的調用例子:
(2).知道遠程計算機名稱:
知道遠程計算機名稱后,利用"Send"方法直接把UDP數據包發送到遠程主機的指定端口號上了,這種調用方式也是最容易的,語法如下:
參數說明:
dgram 要發送的 UDP 數據文報(以字節數組表示)。
bytes 數據文報中的字節數。
hostname 要連接到的遠程主機的名稱。
port 要與其通訊的遠程端口號。
返回值 已發送的字節數。
附上發送數據代碼如下:
private void btnSend_Click(object sender, EventArgs e)
{
Thread t = new Thread(SendMsg);
t.IsBackground = true;
t.Start(sendText.Text);
}
private void SendMsg( object obj )
{
string message = (string)obj;
SendClient = new UdpClient(0);
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(message);
remoteIp = IPAddress.Parse(remoteIPBox.Text);
IPEndPoint iep = new IPEndPoint(remoteIp,portSend);
try
{
SendClient.Send(bytes, bytes.Length, iep);
AddItem(listBoxstatus, string.Format("向{0}發送:{1}", iep, message)); //異步委托顯示數據
clearTextBox();
}
catch(Exception ex)
{
AddItem(listBoxstatus,"發送出錯"+ex.Message);
}
}
接收數據
2.Visual C# UdpClient類接收UDP數據包:
接收UDP數據包使用的是UdpClient中的“Receive"方法。
參數說明:
remoteEP 是一個 IPEndPoint類的實例,它表示網絡中發送此數據包的節點。
附上接收數據的代碼如下:
private void FormChat_Load(object sender, EventArgs e)
{
//創建接收線程
Thread RecivceThread = new Thread(RecivceMsg);
RecivceThread.IsBackground = true;
RecivceThread.Start();
sendText.Focus();
}
private void RecivceMsg()
{
IPEndPoint local = new IPEndPoint(ip,portRecv);
RecviceClient = new UdpClient(local);
IPEndPoint remote = new IPEndPoint(IPAddress.Any, portSend);
while (true)
{
try
{
byte[] recivcedata = RecviceClient.Receive(ref remote);
string strMsg = Encoding.ASCII.GetString(recivcedata, 0, recivcedata.Length);
AddItem(listBoxRecv, string.Format("來自{0}:{1}", remote, strMsg));
}
catch
{
break;
}
}
}
細節注意
1、在Winfrom框架下,在多線程中進行控件操作,就需要使用異常委托方式解決。
2、使用同一台計算機進行調試,ip設置統一,即為:127.0.0.1,端口號不同。
總結
該文章簡單對C#的UDP通訊進行一個講解,簡單入門可以,還有很多需要注意,比如需要加鎖保護數據,使用隊列等等方式對數據進行。再以后的文章中再補充。
