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

发送数据:

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

接收数据:

        /// <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));
            }
        }
posted @ 2010-03-16 10:47  liulun  阅读(3254)  评论(1编辑  收藏  举报