您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“C#怎么使用udp實現(xiàn)消息的接收和發(fā)送”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“C#怎么使用udp實現(xiàn)消息的接收和發(fā)送”吧!
代碼比較簡單,但是別忘記關(guān)閉防火墻進(jìn)行測試。
首先便是服務(wù)端,使用Socket進(jìn)行實現(xiàn),參考代碼如下:
private static Socket udpServer; static void startUdpReceive() { Console.WriteLine("------startUdpReceive--"); udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); udpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.2.106"), 10023)); new Thread(ReceiveMessage) { IsBackground = true }.Start(); } private static void ReceiveMessage() { Console.WriteLine("------ReceiveMessage--"); while (true) { byte[] data = new byte[1024]; EndPoint endPoint = new IPEndPoint(IPAddress.Any, 0); int count = udpServer.ReceiveFrom(data, ref endPoint); if (count > 0) { string message = Encoding.UTF8.GetString(data, 0, count); Console.WriteLine ("-----從ip" + (endPoint as IPEndPoint).Address.ToString() + ":" + (endPoint as IPEndPoint).Port + "Get" + message); } } }
在綁定socket端口的時候,需要提供綁定的ip和端口號,如這里是
udpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.2.106"), 10023));
本機(jī)ip是是192.168.2.106,綁定端口是10023。然后使用while循環(huán)監(jiān)聽消息。對于本機(jī)來說,也可以使用 udpServer.Bind(new IPEndPoint(IPAddress.Any, 10023)); 只綁定端口,對于ip則不限制。
也可以不用Socket而是直接使用UdpClient類來寫接收端,效果類似:
static UdpClient udpcRecv; public static void UdpServices() { try { IPAddress ip = IPAddress.Parse("192.168.2.106"); IPEndPoint remoteIpep = new IPEndPoint(ip, 10023); udpcRecv = new UdpClient(remoteIpep); Thread thrRecv = new Thread(ReceiveMessage22); thrRecv.IsBackground = true; thrRecv.Start(); } catch (Exception ex) { MessageBox.Show("錯誤", "請檢查網(wǎng)絡(luò)"); } } private static void ReceiveMessage22() { IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Any, 0); Console.WriteLine("-----remoteIpep:" + remoteIpep.Address + ":" + remoteIpep.Port); while (true) { try { byte[] bytRecv = udpcRecv.Receive(ref remoteIpep); string message = Encoding.UTF8.GetString( bytRecv, 0, bytRecv.Length); Console.WriteLine("-----reveice message:" + message); } catch (Exception ex) { MessageBox.Show("UDP異常", ex.Message); } } }
接下來是發(fā)送端:
UdpClient udpClient = new UdpClient(); try { udpClient.Connect("192.168.2.106", 10023); Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there??????"); udpClient.Send(sendBytes, sendBytes.Length); } catch (Exception ex) { Console.WriteLine(ex.ToString()); }
如果代碼爆紅則應(yīng)該是導(dǎo)包的問題,加入以下即可。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net.Sockets; using System.Net; using System.Net.NetworkInformation; using System.Management; using System.Threading;
上面都寫好后可以測試了,但是我卻遇到了問題,后面才知道是電腦端防火墻沒開導(dǎo)致,所以和電腦端調(diào)試網(wǎng)絡(luò)通信的時候,需要關(guān)閉防火墻,才能收到數(shù)據(jù)。
面試的時候偶爾會問到UDP和TCP的一個區(qū)別。
TCP是一種面向連接的、可靠的、基于字節(jié)流的傳輸層通信協(xié)議。舉例:打電話,需要雙方都接通,才能進(jìn)行對話。特點:效率低,數(shù)據(jù)傳輸比較安全。
UDP是一種面向無連接的傳輸層通信協(xié)議。舉例:發(fā)短信,不需要雙方建立連接,但是,數(shù)據(jù)報的大小應(yīng)限制在64k以內(nèi)。特點:效率高,數(shù)據(jù)傳輸不安全,容易丟包
然后發(fā)現(xiàn)在網(wǎng)上查找關(guān)于C#運行UDP的實例,確實不好找,雜亂無章。痛定思痛!
進(jìn)行一個簡單的發(fā)送和接收測試。
目前,UDP本人親自用過的場景,客戶端和服務(wù)端需要進(jìn)行數(shù)據(jù)傳輸,但是服務(wù)端,在開始時是連接的別的網(wǎng)絡(luò),切換過來之后,并不能知道當(dāng)前的一個具體的IP地址。但是客戶端的IP地址是固定的,此種場景下,服務(wù)端網(wǎng)絡(luò)切換過來之后,建立UDP服務(wù)端,像指定的客戶端(IP地址和端口號)發(fā)送數(shù)據(jù),即可知道當(dāng)前服務(wù)端的ip地址。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MyTest.UDP { public partial class UDP_Sever : Form { IPEndPoint remotePoint; UdpClient sever = null; public UDP_Sever() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { IPAddress remoteIP = IPAddress.Parse(textBox1.Text.Trim()); //假設(shè)發(fā)送給這個IP int remotePort =int.Parse(textBox2.Text.Trim()); remotePoint = new IPEndPoint(remoteIP, remotePort);//實例化一個遠(yuǎn)程端點 sever = new UdpClient(); } private void button2_Click(object sender, EventArgs e) { if (!string.IsNullOrWhiteSpace(textBox3.Text.Trim())) { string sendString = textBox3.Text.Trim();//要發(fā)送的字符串 byte[] sendData = Encoding.Default.GetBytes(sendString);//要發(fā)送的字節(jié)數(shù)組 sever.Send(sendData, sendData.Length, remotePoint);//將數(shù)據(jù)發(fā)送到遠(yuǎn)程端點 textBox3.Text = ""; } } private void UDP_Sever_FormClosing(object sender, FormClosingEventArgs e) { sever.Close(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace MyTest.UDP { public partial class UDP_Client : Form { UdpClient client = null; IPEndPoint remotePoint; string receiveString = null; byte[] receiveData = null; public UDP_Client() { InitializeComponent(); CheckForIllegalCrossThreadCalls = false; } private void button1_Click(object sender, EventArgs e) { //實例化一個遠(yuǎn)程端點,IP和端口可以隨意指定,等調(diào)用client.Receive(ref remotePoint)時會將該端點改成真正發(fā)送端端點 remotePoint = new IPEndPoint(IPAddress.Any, 0); client = new UdpClient(int.Parse(textBox2.Text.Trim())); Thread thread = new Thread(Revice); thread.IsBackground = true; thread.Start(); } private void Revice() { while (true) { receiveData = client.Receive(ref remotePoint);//接收數(shù)據(jù) receiveString = Encoding.Default.GetString(receiveData); listBox1.Items.Add(remotePoint.Address.ToString()+":"+ receiveString); } } } }
到此,相信大家對“C#怎么使用udp實現(xiàn)消息的接收和發(fā)送”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。