C#使用udp如何實現(xiàn)消息的接收和發(fā)送
使用udp實現(xiàn)消息的接收和發(fā)送
代碼比較簡單,但是別忘記關閉防火墻進行測試。
首先便是服務端,使用Socket進行實現(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));
本機ip是是192.168.2.106,綁定端口是10023。然后使用while循環(huán)監(jiān)聽消息。對于本機來說,也可以使用 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)絡"); ? ? ? ? ? ? } ? ? ? ? ? } ? ? ? ? ? ? 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()); ? ? ? ? ? ? }
如果代碼爆紅則應該是導包的問題,加入以下即可。
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;
上面都寫好后可以測試了,但是我卻遇到了問題,后面才知道是電腦端防火墻沒開導致,所以和電腦端調(diào)試網(wǎng)絡通信的時候,需要關閉防火墻,才能收到數(shù)據(jù)。
C# 運用UDP
面試的時候偶爾會問到UDP和TCP的一個區(qū)別。
- TCP是一種面向連接的、可靠的、基于字節(jié)流的傳輸層通信協(xié)議。舉例:打電話,需要雙方都接通,才能進行對話。特點:效率低,數(shù)據(jù)傳輸比較安全。
- UDP是一種面向無連接的傳輸層通信協(xié)議。舉例:發(fā)短信,不需要雙方建立連接,但是,數(shù)據(jù)報的大小應限制在64k以內(nèi)。特點:效率高,數(shù)據(jù)傳輸不安全,容易丟包
然后發(fā)現(xiàn)在網(wǎng)上查找關于C#運行UDP的實例,確實不好找,雜亂無章。痛定思痛!
進行一個簡單的發(fā)送和接收測試。
目前,UDP本人親自用過的場景,客戶端和服務端需要進行數(shù)據(jù)傳輸,但是服務端,在開始時是連接的別的網(wǎng)絡,切換過來之后,并不能知道當前的一個具體的IP地址。但是客戶端的IP地址是固定的,此種場景下,服務端網(wǎng)絡切換過來之后,建立UDP服務端,像指定的客戶端(IP地址和端口號)發(fā)送數(shù)據(jù),即可知道當前服務端的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()); //假設發(fā)送給這個IP int remotePort =int.Parse(textBox2.Text.Trim()); remotePoint = new IPEndPoint(remoteIP, remotePort);//實例化一個遠程端點 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ā)送到遠程端點 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) { //實例化一個遠程端點,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); } } } }
親測有效!
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
C#中的Task.WaitAll和Task.WaitAny方法介紹
這篇文章介紹了C#中的Task.WaitAll和Task.WaitAny方法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-04-04UnityShader使用速度映射圖實現(xiàn)運動模糊
這篇文章主要為大家詳細介紹了UnityShader使用速度映射圖實現(xiàn)運動模糊,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-02-02SQLite之C#版 System.Data.SQLite使用方法
這篇文章主要介紹了SQLite之C#版 System.Data.SQLite使用方法,需要的朋友可以參考下2020-10-10