C#使用udp如何實(shí)現(xiàn)消息的接收和發(fā)送
使用udp實(shí)現(xiàn)消息的接收和發(fā)送
代碼比較簡(jiǎn)單,但是別忘記關(guān)閉防火墻進(jìn)行測(cè)試。
首先便是服務(wù)端,使用Socket進(jìn)行實(shí)現(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端口的時(shí)候,需要提供綁定的ip和端口號(hào),如這里是
udpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.2.106"), 10023));本機(jī)ip是是192.168.2.106,綁定端口是10023。然后使用while循環(huán)監(jiān)聽消息。對(duì)于本機(jī)來(lái)說(shuō),也可以使用 udpServer.Bind(new IPEndPoint(IPAddress.Any, 10023)); 只綁定端口,對(duì)于ip則不限制。
也可以不用Socket而是直接使用UdpClient類來(lái)寫接收端,效果類似:
? ? ? ? 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("錯(cuò)誤", "請(qǐng)檢查網(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);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }接下來(lái)是發(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)包的問(wèn)題,加入以下即可。
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;
上面都寫好后可以測(cè)試了,但是我卻遇到了問(wèn)題,后面才知道是電腦端防火墻沒(méi)開導(dǎo)致,所以和電腦端調(diào)試網(wǎng)絡(luò)通信的時(shí)候,需要關(guān)閉防火墻,才能收到數(shù)據(jù)。
C# 運(yùn)用UDP
面試的時(shí)候偶爾會(huì)問(wèn)到UDP和TCP的一個(gè)區(qū)別。
- TCP是一種面向連接的、可靠的、基于字節(jié)流的傳輸層通信協(xié)議。舉例:打電話,需要雙方都接通,才能進(jìn)行對(duì)話。特點(diǎn):效率低,數(shù)據(jù)傳輸比較安全。
- UDP是一種面向無(wú)連接的傳輸層通信協(xié)議。舉例:發(fā)短信,不需要雙方建立連接,但是,數(shù)據(jù)報(bào)的大小應(yīng)限制在64k以內(nèi)。特點(diǎn):效率高,數(shù)據(jù)傳輸不安全,容易丟包
然后發(fā)現(xiàn)在網(wǎng)上查找關(guān)于C#運(yùn)行UDP的實(shí)例,確實(shí)不好找,雜亂無(wú)章。痛定思痛!
進(jìn)行一個(gè)簡(jiǎn)單的發(fā)送和接收測(cè)試。
目前,UDP本人親自用過(guò)的場(chǎng)景,客戶端和服務(wù)端需要進(jìn)行數(shù)據(jù)傳輸,但是服務(wù)端,在開始時(shí)是連接的別的網(wǎng)絡(luò),切換過(guò)來(lái)之后,并不能知道當(dāng)前的一個(gè)具體的IP地址。但是客戶端的IP地址是固定的,此種場(chǎng)景下,服務(wù)端網(wǎng)絡(luò)切換過(guò)來(lái)之后,建立UDP服務(wù)端,像指定的客戶端(IP地址和端口號(hào))發(fā)送數(shù)據(jù),即可知道當(dāng)前服務(wù)端的ip地址。
服務(wù)端界面

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ā)送給這個(gè)IP
int remotePort =int.Parse(textBox2.Text.Trim());
remotePoint = new IPEndPoint(remoteIP, remotePort);//實(shí)例化一個(gè)遠(yuǎn)程端點(diǎ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)程端點(diǎ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)
{
//實(shí)例化一個(gè)遠(yuǎn)程端點(diǎn),IP和端口可以隨意指定,等調(diào)用client.Receive(ref remotePoint)時(shí)會(huì)將該端點(diǎn)改成真正發(fā)送端端點(diǎn)
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è)有效!
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
C#中的Task.WaitAll和Task.WaitAny方法介紹
這篇文章介紹了C#中的Task.WaitAll和Task.WaitAny方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-04-04
C#使用ZXing.Net實(shí)現(xiàn)識(shí)別二維碼和條碼
ZXing用Java實(shí)現(xiàn)的多種格式的一維二維條碼圖像處理庫(kù),而ZXing.Net是其.Net版本的實(shí)現(xiàn),本文主要為大家詳細(xì)介紹了如何使用ZXing.Net實(shí)現(xiàn)識(shí)別二維碼和條碼,需要的可以參考下2024-01-01
深入解析C#設(shè)計(jì)模式中對(duì)橋接模式的具體運(yùn)用
這篇文章主要介紹了C#設(shè)計(jì)模式中對(duì)橋接模式的具體運(yùn)用,橋接模式所強(qiáng)調(diào)的解耦在代碼維護(hù)中非常有用,需要的朋友可以參考下2016-02-02
UnityShader使用速度映射圖實(shí)現(xiàn)運(yùn)動(dòng)模糊
這篇文章主要為大家詳細(xì)介紹了UnityShader使用速度映射圖實(shí)現(xiàn)運(yùn)動(dòng)模糊,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-02-02
SQLite之C#版 System.Data.SQLite使用方法
這篇文章主要介紹了SQLite之C#版 System.Data.SQLite使用方法,需要的朋友可以參考下2020-10-10
C# 創(chuàng)建Excel氣泡圖的實(shí)例代碼
這篇文章主要介紹了C# 創(chuàng)建Excel氣泡圖的實(shí)例代碼,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01
c# 使用WebRequest實(shí)現(xiàn)多文件上傳
這篇文章主要介紹了c# 使用WebRequest實(shí)現(xiàn)多文件上傳的方法,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03

