UDP 网络通信 C#
c# UDP 网络通信
2023-09-27 14:23:42 时间
接收端
using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Windows.Forms; namespace UDPReceiveTest { public partial class Form1 : Form { public UdpClient udpClient; public Thread UdpThread; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { if (UdpThread != null) { UdpThread.Abort(); Thread.Sleep(TimeSpan.FromMilliseconds(500d)); } System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false; if (udpClient != null) { UdpThread.Abort(); Thread.Sleep(TimeSpan.FromMilliseconds(500d)); udpClient.Close(); } try { udpClient = new UdpClient(int.Parse(txtPort.Text)); UdpThread = new Thread(new ThreadStart(UdpReciveThread)); UdpThread.Start(); } catch (Exception y) { MessageBox.Show(this, y.Message, "Error", MessageBoxButtons.OK,MessageBoxIcon.Error); this.Dispose(true); } } private void button1_Click(object sender, EventArgs e) { txtMessage.Text = string.Empty; } delegate void SetTextCallback(IPEndPoint remoteHost, byte[] buf, string bufs); //接收数据线程 void UdpReciveThread() { IPHostEntry oIPHost = Dns.GetHostEntry(Environment.MachineName); IPEndPoint remoteHost = new IPEndPoint(IPAddress.Any, 0); while (udpClient != null &&Thread.CurrentThread.ThreadState.Equals(ThreadState.Running)) { try { byte[] buf = udpClient.Receive(ref remoteHost); string bufs = Encoding.UTF8.GetString(buf); txtMessage.Text += remoteHost.Address.ToString() + "说:" +Environment.NewLine; txtMessage.Text += bufs + Environment.NewLine; } catch (Exception y) { } } txtMessage.Text += "结束..." + (char)13; } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { try { udpClient.Close(); UdpThread.Abort(); } catch { } } } }
发送端
using System; using System.Net.Sockets; using System.Text; using System.Windows.Forms; namespace UDPSendTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnSend_Click(object sender, EventArgs e) { try { UdpClient uc = new UdpClient(txtIP.Text, int.Parse(txtPort.Text)); byte[] sendbuf = Encoding.UTF8.GetBytes(txtMessage.Text); uc.Send(sendbuf, sendbuf.Length); } catch (Exception y) { MessageBox.Show(this, y.Message, "发送失败", MessageBoxButtons.OK,MessageBoxIcon.Hand); } } } }
相关文章
- C#继承的执行顺序
- C#控件StatusStrip使用
- Tutorial: Create a Windows Machine Learning UWP application (C#)
- 职责链模式实例(C#)
- C# 波形绘制
- C#变量的作用域
- C#图像处理-OpenCVSharp教程(九) OpenCVSharp读取或修改图像像素值
- 【C#进阶】C# 不安全代码
- C#问题——interface && class
- c# 000格式string补位
- Vs2017 C#操作xml(1)
- 【知识积累】DES算法之C#加密&Java解密
- .NET Core(C#) EPPlus读取Excel(.xlsx)文件的方法及示例代码
- C# - openxml 操作excel - '“System.IO.Packaging.Package”在未被引用的程序集中定义'
- C# 强转空会不会出现异常
- C# 性能分析 反射 VS 配置文件 VS 预编译
- C# GUID ToString
- 如何使用 C# 爬虫获得专栏博客更新排行
- C#读写文本文件
- Asp.net(c#)常用文件操作类封装 移动 复制 删除 上传 下载等