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;
public int Port { get; private set; } = -1;
public bool IsOpen => _isRunning;
public Udp_Client(EventHandler<UdpMsg> callbackEventDataReceived)
{
this.callbackEventDataReceived = callbackEventDataReceived;
}
public bool OpenClient(int port)
{
Port = port;
Open();
return IsOpen;
}
public bool OpenClient()
{
Open();
return IsOpen;
}
private void Open()
{
try
{
if (IsOpen)
{
CloseClient();
}
_client = Port < 0 ? new UdpClient() : new UdpClient(Port);
_isRunning = true;
new Task(Received).Start();
}
catch (Exception ex)
{
}
}
public void CloseClient()
{
_isRunning = false;
_client?.Close();
_client = null;
}
public void Send(byte[] data, IPEndPoint endPoint)
{
if (IsOpen == false) return;
_client.Send(data, data.Length, endPoint);
}
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
{
public IPEndPoint RemoteEP { get; set; }
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
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
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();
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";
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;
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";
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 = "目标端口";
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;
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;
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;
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 = "端口";
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";
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;
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 = "";
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;
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 = "消息内容";
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;
}
}