網站首頁 編程語言 正文
使用udp實現消息的接收和發送
代碼比較簡單,但是別忘記關閉防火墻進行測試。
首先便是服務端,使用Socket進行實現,參考代碼如下:
? ? ? ? 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循環監聽消息。對于本機來說,也可以使用 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("錯誤", "請檢查網絡");
? ? ? ? ? ? }
?
? ? ? ? }
?
?
? ? ? ? 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);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
接下來是發送端:
? ? ? ? ? ? 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;
上面都寫好后可以測試了,但是我卻遇到了問題,后面才知道是電腦端防火墻沒開導致,所以和電腦端調試網絡通信的時候,需要關閉防火墻,才能收到數據。
C# 運用UDP
面試的時候偶爾會問到UDP和TCP的一個區別。
- TCP是一種面向連接的、可靠的、基于字節流的傳輸層通信協議。舉例:打電話,需要雙方都接通,才能進行對話。特點:效率低,數據傳輸比較安全。
- UDP是一種面向無連接的傳輸層通信協議。舉例:發短信,不需要雙方建立連接,但是,數據報的大小應限制在64k以內。特點:效率高,數據傳輸不安全,容易丟包
然后發現在網上查找關于C#運行UDP的實例,確實不好找,雜亂無章。痛定思痛!
進行一個簡單的發送和接收測試。
目前,UDP本人親自用過的場景,客戶端和服務端需要進行數據傳輸,但是服務端,在開始時是連接的別的網絡,切換過來之后,并不能知道當前的一個具體的IP地址。但是客戶端的IP地址是固定的,此種場景下,服務端網絡切換過來之后,建立UDP服務端,像指定的客戶端(IP地址和端口號)發送數據,即可知道當前服務端的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()); //假設發送給這個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();//要發送的字符串
byte[] sendData = Encoding.Default.GetBytes(sendString);//要發送的字節數組
sever.Send(sendData, sendData.Length, remotePoint);//將數據發送到遠程端點
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和端口可以隨意指定,等調用client.Receive(ref remotePoint)時會將該端點改成真正發送端端點
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);//接收數據
receiveString = Encoding.Default.GetString(receiveData);
listBox1.Items.Add(remotePoint.Address.ToString()+":"+ receiveString);
}
}
}
}
親測有效!
總結
原文鏈接:https://blog.csdn.net/bawang_cn/article/details/120139559
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2022-11-15 python內置模塊OS?實現SHELL端文件處理器_python
- 2022-10-08 C#中Timer實現Tick使用精度的問題_C#教程
- 2022-12-13 Redis?Hash序列化存儲的問題及解決方案_Redis
- 2023-12-13 pyinstaller打包exe時報錯問題記錄[makespec options not valid
- 2022-07-01 Python判斷Nan值的五種方式小結_python
- 2023-01-07 詳解C++11中綁定器bind的原理與使用_C 語言
- 2023-05-18 Kotlin?ViewModelProvider.Factory的使用實例詳解_Android
- 2022-07-09 kernel劫持modprobe?path內容詳解_C 語言
- 欄目分類
-
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支