前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >通过UDP的组播方式收发数据

通过UDP的组播方式收发数据

作者头像
liulun
发布2022-05-09 11:45:00
1.2K0
发布2022-05-09 11:45:00
举报
文章被收录于专栏:liulun

客户端代码

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace UDPTest
{
    public partial class Form1 : Form
    {
        private UdpClient udpSend;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            udpSend = new UdpClient();
            udpSend.EnableBroadcast = true;//是否可以发送和接收广播
            IPEndPoint iep = new IPEndPoint(IPAddress.Parse("224.100.0.10"), 8001);
            byte[] data = Encoding.UTF8.GetBytes(richTextBox1.Text);
            udpSend.Send(data, data.Length, iep);
            richTextBox1.Clear();
        }
    }
}

服务端代码

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.Net.Sockets;

namespace UDPTest2
{
    public partial class Form1 : Form
    {
        
        UdpClient udpReceive;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            byte[] data = null;
            udpReceive = new UdpClient(8001);
            udpReceive.JoinMulticastGroup(IPAddress.Parse("224.100.0.10"), 50);//添加到多路广播组,50为路由器跳数
            IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0);
            while (true)
            {
                data = udpReceive.Receive(ref iep);
                string str = Encoding.UTF8.GetString(data, 0, data.Length);
                MessageBox.Show(iep.ToString() + ":" + str);
            }
        }
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2010-03-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档