当前位置: 首页 > news >正文

C#UDP协议客户端工具类

C#UDP协议客户端工具类

  • 1 工具类(Udp_Client.cs)
  • 2 测试窗体
    • 2.1 窗体示例
    • 2.2 Form.cs
    • 2.3 Form1.Designer.cs

1 工具类(Udp_Client.cs)

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace Demo_UDPTest
{
    public class Udp_Client
    {
        private UdpClient _client;
        private EventHandler<UdpMsg> callbackEventDataReceived;
        private bool _isRunning;

        /// <summary>
        /// 本机客户端接受数据端口
        /// </summary>
        public int Port { get; private set; } = -1;

        /// <summary>
        /// 客户端运行状态
        /// </summary>
        public bool IsOpen => _isRunning;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="callbackEventDataReceived">接受缓冲区回调事件</param>
        public Udp_Client(EventHandler<UdpMsg> callbackEventDataReceived)
        {
            this.callbackEventDataReceived = callbackEventDataReceived;
        }

        /// <summary>
        /// 创建发送/接收客户端
        /// </summary>
        /// <param name="port"></param>
        /// <returns></returns>
        public bool OpenClient(int port)
        {
            Port = port;
            Open();
            return IsOpen;
        }

        /// <summary>
        /// 创建发送客户端
        /// </summary>
        /// <returns></returns>
        public bool OpenClient()
        {
            Open();
            return IsOpen;
        }

        /// <summary>
        /// 打开客户端
        /// </summary>
        private void Open()
        {
            try
            {
                if (IsOpen)
                {
                    CloseClient();
                }
                _client = Port < 0 ? new UdpClient() : new UdpClient(Port);
                _isRunning = true;
                // 客户端创建一个新的线程来处理通信
                new Task(Received).Start();
            }
            catch (Exception ex)
            {
            }
        }

        /// <summary>
        /// 关闭客户端
        /// </summary>
        public void CloseClient()
        {
            _isRunning = false;
            _client?.Close();
            _client = null;
        }

        /// <summary>
        /// 向目标端口发送数据
        /// </summary>
        /// <param name="data">数据报</param>
        /// <param name="endPoint">表示要将数据报发送到的主机和端口</param>
        public void Send(byte[] data, IPEndPoint endPoint)
        {
            if (IsOpen == false) return;

            //string message = "Hello, UDP Receiver!";
            //byte[] data = Encoding.UTF8.GetBytes(message);

            // 发送数据
            _client.Send(data, data.Length, endPoint);
        }

        /// <summary>
        /// 接受来自远程主机发送的消息
        /// </summary>
        public void Received()
        {
            while (_isRunning)
            {
                try
                {
                    IPEndPoint senderEndpoint = new IPEndPoint(IPAddress.Any, 0);
                    // 接收数据
                    byte[] buffer = _client.Receive(ref senderEndpoint);
                    callbackEventDataReceived?.Invoke(null, new UdpMsg(senderEndpoint, buffer));
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"端口:{Port},{ex.Message}");
                }
            }
        }

        public class UdpMsg : EventArgs
        {
            /// <summary>
            /// 远程主机地址以及端口
            /// </summary>
            public IPEndPoint RemoteEP { get; set; }

            /// <summary>
            /// 数据包
            /// </summary>
            public byte[] Data { get; set; }

            public UdpMsg(IPEndPoint remoteEp, byte[] data)
            {
                RemoteEP = remoteEp;
                Data = data;
            }
        }
    }
}

2 测试窗体

2.1 窗体示例

在这里插入图片描述

2.2 Form.cs

using System;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace Demo_UDPTest
{
    public partial class Form1 : Form
    {
        private Udp_Client _client;

        private int HostPort => int.Parse(txt_HostPort.Text);
        private IPEndPoint RemoteEp => new IPEndPoint(IPAddress.Parse(txt_IP.Text), int.Parse(txt_Port.Text));

        private readonly Random _random = new Random();

        public Form1()
        {
            InitializeComponent();
            Init();
        }

        public Form1(string remotePort)
        {
            InitializeComponent();
            txt_Port.Text = remotePort;
            Init();
        }

        private void Init()
        {
            this.Text = "UDP客户端";
            btnOpenNewClient.Click += (sender, args) => new Form1(txt_HostPort.Text).Show();
            btnOpenClient.Click += (sender, args) => OpenClient();
            btnCloseClient.Click += (sender, args) => CloseClient();
            btn_Send.Click += (sender, args) => SendMessage();

            txt_HostPort.Text = _random.Next(2000, 20000).ToString();
            txt_Msg.Text = txt_HostPort.Text;
            OpenClient();
        }

        public static void RefreshForm(Form form, Action eventRefresh)
        {
            if (form.InvokeRequired)
            {
                form.Invoke(new EventHandler(delegate { RefreshForm(form, eventRefresh); }));
            }
            else
            {
                eventRefresh?.Invoke();
            }
        }

        private void SetButtionEnabled()
        {
            RefreshForm(this, () =>
            {
                btnOpenClient.Enabled = _client?.IsOpen == false;
                btnCloseClient.Enabled = _client?.IsOpen == true;
            });
        }

        private void AppendText(object sender, Udp_Client.UdpMsg e)
        {
            RefreshForm(this, () =>
            {
                richTextBox1.AppendText(e.RemoteEP.ToString());
                richTextBox1.AppendText("\t");
                richTextBox1.AppendText(Encoding.UTF8.GetString(e.Data));
                richTextBox1.AppendText(Environment.NewLine);
                richTextBox1.ScrollToCaret();
            });
        }

        private void OpenClient()
        {
            _client = new Udp_Client(AppendText);
            _client?.OpenClient(HostPort);
            SetButtionEnabled();
        }

        private void CloseClient()
        {
            _client?.CloseClient();
            SetButtionEnabled();
        }

        private void SendMessage()
        {
            string message = txt_Msg.Text;
            byte[] data = Encoding.UTF8.GetBytes(message);
            _client?.Send(data, RemoteEp);
        }

    }
}


2.3 Form1.Designer.cs

namespace Demo_UDPTest
{
    partial class Form1
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.txt_IP = new System.Windows.Forms.TextBox();
            this.txt_Port = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.btnOpenClient = new System.Windows.Forms.Button();
            this.btnCloseClient = new System.Windows.Forms.Button();
            this.txt_HostPort = new System.Windows.Forms.TextBox();
            this.label3 = new System.Windows.Forms.Label();
            this.txt_Msg = new System.Windows.Forms.TextBox();
            this.btn_Send = new System.Windows.Forms.Button();
            this.richTextBox1 = new System.Windows.Forms.RichTextBox();
            this.btnOpenNewClient = new System.Windows.Forms.Button();
            this.label4 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // txt_IP
            // 
            this.txt_IP.Location = new System.Drawing.Point(24, 154);
            this.txt_IP.Name = "txt_IP";
            this.txt_IP.Size = new System.Drawing.Size(100, 21);
            this.txt_IP.TabIndex = 0;
            this.txt_IP.Text = "127.0.0.1";
            // 
            // txt_Port
            // 
            this.txt_Port.Location = new System.Drawing.Point(24, 220);
            this.txt_Port.Name = "txt_Port";
            this.txt_Port.Size = new System.Drawing.Size(100, 21);
            this.txt_Port.TabIndex = 0;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(22, 139);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(41, 12);
            this.label1.TabIndex = 1;
            this.label1.Text = "目标IP";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(22, 195);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(53, 12);
            this.label2.TabIndex = 1;
            this.label2.Text = "目标端口";
            // 
            // btnOpenClient
            // 
            this.btnOpenClient.Location = new System.Drawing.Point(46, 85);
            this.btnOpenClient.Name = "btnOpenClient";
            this.btnOpenClient.Size = new System.Drawing.Size(60, 23);
            this.btnOpenClient.TabIndex = 2;
            this.btnOpenClient.Text = "打开";
            this.btnOpenClient.UseVisualStyleBackColor = true;
            // 
            // btnCloseClient
            // 
            this.btnCloseClient.Location = new System.Drawing.Point(112, 85);
            this.btnCloseClient.Name = "btnCloseClient";
            this.btnCloseClient.Size = new System.Drawing.Size(60, 23);
            this.btnCloseClient.TabIndex = 2;
            this.btnCloseClient.Text = "关闭";
            this.btnCloseClient.UseVisualStyleBackColor = true;
            // 
            // txt_HostPort
            // 
            this.txt_HostPort.Location = new System.Drawing.Point(60, 52);
            this.txt_HostPort.Name = "txt_HostPort";
            this.txt_HostPort.Size = new System.Drawing.Size(100, 21);
            this.txt_HostPort.TabIndex = 0;
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(22, 55);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(29, 12);
            this.label3.TabIndex = 1;
            this.label3.Text = "端口";
            // 
            // txt_Msg
            // 
            this.txt_Msg.Location = new System.Drawing.Point(24, 287);
            this.txt_Msg.Name = "txt_Msg";
            this.txt_Msg.Size = new System.Drawing.Size(161, 21);
            this.txt_Msg.TabIndex = 3;
            this.txt_Msg.Text = "ABC";
            // 
            // btn_Send
            // 
            this.btn_Send.Location = new System.Drawing.Point(125, 314);
            this.btn_Send.Name = "btn_Send";
            this.btn_Send.Size = new System.Drawing.Size(60, 23);
            this.btn_Send.TabIndex = 2;
            this.btn_Send.Text = "发送";
            this.btn_Send.UseVisualStyleBackColor = true;
            // 
            // richTextBox1
            // 
            this.richTextBox1.Location = new System.Drawing.Point(204, 52);
            this.richTextBox1.Name = "richTextBox1";
            this.richTextBox1.Size = new System.Drawing.Size(258, 311);
            this.richTextBox1.TabIndex = 4;
            this.richTextBox1.Text = "";
            // 
            // btnOpenNewClient
            // 
            this.btnOpenNewClient.Location = new System.Drawing.Point(204, 12);
            this.btnOpenNewClient.Name = "btnOpenNewClient";
            this.btnOpenNewClient.Size = new System.Drawing.Size(258, 23);
            this.btnOpenNewClient.TabIndex = 5;
            this.btnOpenNewClient.Text = "启动新客户端";
            this.btnOpenNewClient.UseVisualStyleBackColor = true;
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(22, 272);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(53, 12);
            this.label4.TabIndex = 1;
            this.label4.Text = "消息内容";
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(493, 378);
            this.Controls.Add(this.btnOpenNewClient);
            this.Controls.Add(this.richTextBox1);
            this.Controls.Add(this.txt_Msg);
            this.Controls.Add(this.btn_Send);
            this.Controls.Add(this.btnCloseClient);
            this.Controls.Add(this.btnOpenClient);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.txt_HostPort);
            this.Controls.Add(this.txt_Port);
            this.Controls.Add(this.txt_IP);
            this.Name = "Form1";
            this.Text = "UDP客户端";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox txt_IP;
        private System.Windows.Forms.TextBox txt_Port;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Button btnOpenClient;
        private System.Windows.Forms.Button btnCloseClient;
        private System.Windows.Forms.TextBox txt_HostPort;
        private System.Windows.Forms.Label label3;
        private System.Windows.Forms.TextBox txt_Msg;
        private System.Windows.Forms.Button btn_Send;
        private System.Windows.Forms.RichTextBox richTextBox1;
        private System.Windows.Forms.Button btnOpenNewClient;
        private System.Windows.Forms.Label label4;
    }
}


相关文章:

  • C#实现存储数据到Redis
  • 运行小程序报错
  • Leetcode 3508. Implement Router
  • Java数据结构的基础用法
  • 嵌入式AI开源生态指南:从框架到应用的全面解析
  • JavaScript学习教程,从入门到精通,JavaScript 基础语法全面指南(5)
  • 2025.4.6总结
  • 低空经济基础设施建设方向与展望
  • 深入详解流形学习中的几何解释
  • 机器学习/深度学习
  • HTML语言的数据可视化
  • deepseek为采用JAVA重构模型运营平台vLLM和SGLang指定的计划
  • 【学习笔记】Ruckig: 高效实时运动规划库
  • 如何获取oracle cloud永久免费的vps(4C/24G)?
  • 机器学习的一百个概念(10)假阳性率
  • Spring 中的 bean 生命周期
  • 数据对象:DTO、DO、PO和 BO的区别和关系
  • 用 C++ 写汉诺塔程序
  • 从零开始的编程-java篇1.6.3
  • 医院大数据处理的主要痛点分析
  • 网站在线布局/seo优化的主要内容
  • 网站收缩栏/网推资源渠道
  • 如何申请域名做网站知乎/万网域名注册查询
  • 如何用asp做网站/seo在线培训机构排名
  • 哪家公司做网站不错/百度com打开
  • 3有免费建网站/河南关键词优化搜索