UDP广播的方式收发数据(C#)

2022-05-09 11:45:17 浏览数 (1)

发送数据:

代码语言:javascript复制
        /// <summary>
        /// 发送信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            UdpClient client = new UdpClient(AddressFamily.InterNetwork);
            IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 9095);
            byte[] buffer = Encoding.UTF8.GetBytes(richTextBox1.Text);
            client.Send(buffer, buffer.Length, iep);
            client.Close();
        }

接收数据:

代码语言:javascript复制
        /// <summary>
        /// 接收信息
        /// </summary>
        private void RecvMessage()
        {            
            IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9095);
            udpReceive = new UdpClient(iep);
            byte[] data;
            while (flag)
            {
                data = udpReceive.Receive(ref iep);
                MessageBox.Show(Encoding.UTF8.GetString(data));
            }
        }

0 人点赞