c# UDP通过广播实现群发功能

using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//添加的命名空间引用
using System.Net;
using System.Net.Sockets;
using System.Threading;

//UDP通过广播实现群发功能
namespace BroadcastExample
{
    public partial class Form1 : Form
    {
        delegate void AppendStringCallback(string text);
        AppendStringCallback appendstringcallback;
        //使用的接收端口 51008
        /// <summary>
        /// 端口号
        /// </summary>
        private int port = 51008;

        /// <summary>
        /// udp连接对象
        /// </summary>
        private UdpClient udpclient;

        public Form1()
        {
            InitializeComponent();
            appendstringcallback = new AppendStringCallback(AppendString);
        }

        /// <summary>
        /// 委托对象的处理过程
        /// </summary>
        /// <param name="text"></param>
        private void AppendString(string text)
        {
            if (richtextBox2.InvokeRequired == true)
            {
                this.Invoke(appendstringcallback, text);
            }
            else
            {
                richtextBox2.AppendText(text + "/r/n");
            }
        }

        /// <summary>
        /// 在后台运行的接收线程
        /// </summary>
        private void RecData()
        {
            //本机指定端口接收
            udpclient = new UdpClient(port);
            IPEndPoint remote = null;
            //接收从远程主机发送过来的信息
            while (true)
            {
                try
                {
                    //关闭udpclient时此句会产生异常
                    byte[] bytes = udpclient.Receive(ref remote);
                    string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
                    AppendString(string.Format("来自{0}:{1}", remote, str));
                }
                catch
                {
                    //退出循环,结束线程
                    break;
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //创建一个线程接收接收远程主机发来的信息
            Thread mythread = new Thread(new ThreadStart(RecData));
            //将线程设为后台运行
            mythread.IsBackground = true;
            mythread.Start();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            udpclient.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            UdpClient myUdpclient = new UdpClient();

            
            try
            {
                IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, port);
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(textBox1.Text);
                myUdpclient.Send(bytes, bytes.Length, iep);
                textBox1.Clear();
                myUdpclient.Close();
                textBox1.Focus();
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, "发送失败");
            }
            finally
            {
                myUdpclient.Close();
            }
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用C#编程语言来接收UDP广播消息。丢包可能是由于网络延迟或其他因素引起的。为了减少丢包的可能性,你可以采取以下措施: 1. 使用适当的缓冲区大小:确保你的接收缓冲区足够大,以容纳接收到的数据。如果缓冲区太小,可能会导致数据丢失。 2. 设置超时时间:在接收UDP数据之前,你可以设置一个适当的超时时间。如果在超时时间内未收到数据,可以进行重试或采取其他措施。 3. 错误处理和重试:当接收到错误或丢包时,你可以处理这些错误并进行重试。例如,你可以重新发送请求或重新连接到广播源。 下面是一个简单的示例代码,展示了如何使用C#接收UDP广播消息: ```csharp using System; using System.Net; using System.Net.Sockets; class Program { static void Main() { // 创建UDP客户端 UdpClient udpClient = new UdpClient(); udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); // 设置端口和IP地址 int port = 1234; IPAddress ipAddress = IPAddress.Any; // 绑定端口和IP地址 udpClient.Client.Bind(new IPEndPoint(ipAddress, port)); try { while (true) { // 接收UDP数据报文 byte[] data = udpClient.Receive(ref new IPEndPoint(IPAddress.Any, 0)); // 处理接收到的数据 Console.WriteLine(Encoding.UTF8.GetString(data)); } } catch (Exception ex) { // 处理异常 Console.WriteLine(ex.ToString()); } finally { // 关闭UDP客户端 udpClient.Close(); } } } ``` 你可以根据自己的需求进行修改和优化。希望能对你有所帮助!如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值