zoukankan      html  css  js  c++  java
  • 通过UDP的组播方式收发数据

    客户端代码

    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();
            }
        }
    }
    
    

    服务端代码

    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);
                }
            }
        }
    }
    
  • 相关阅读:
    24张图,九大数据结构安排得明明白白
    mysql中的mvcc解读
    常见电商项目的数据库表设计(MySQL版)
    两万字深度介绍分布式系统原理,一文入魂
    使用消息中间件时,如何保证消息仅仅被消费一次?
    GCC/G++选项 -Wl,-Bstatic和-Wl,-Bdynamic
    sql 练习
    设计模式-单例模式
    设计模式-抽象工厂模式
    设计模式-工厂方法模式
  • 原文地址:https://www.cnblogs.com/liulun/p/1686518.html
Copyright © 2011-2022 走看看