C#之UDP通訊

簡介

C#中的udp通訊關鍵類:Udpclient,它位於命名空間System.Net.Sockets中,發送接收都是UdpClient類,html

命名空間

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;
            }
        }
    }

細節注意

一、在Winfrom框架下,在多線程中進行控件操做,就須要使用異常委託方式解決。調試

二、使用同一臺計算機進行調試,ip設置統一,即爲:127.0.0.1,端口號不一樣。code

總結

該文章簡單對C#的UDP通信進行一個講解,簡單入門能夠,還有不少須要注意,好比須要加鎖保護數據,使用隊列等等方式對數據進行。再之後的文章中再補充。orm

相關文章
相關標籤/搜索