C# 实现Udp广播

2019-04-15 15:55发布

   这是一个c#实现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.Threading; namespace UdpBroadcast { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { CheckForIllegalCrossThreadCalls = false; } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { System.Environment.Exit(0); } private void button1_Click(object sender, EventArgs e) { SendMsg(); } private void timer1_Tick(object sender, EventArgs e) { //一直发送 SendMsg(); } void SendMsg() { // 发送消息,本机ip IPAddress ip = IPAddress.Parse("192.168.2.112"); UdpClient client = new UdpClient(new IPEndPoint(ip, int.Parse(textBox2.Text))); IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(textBox1.Text), int.Parse(textBox2.Text)); byte[] buf = Encoding.Default.GetBytes(textBox3.Text); client.Send(buf, buf.Length, endpoint); client.Close(); } void RecvThread() { // 接受数据 UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Any, int.Parse(textBox5.Text))); IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, int.Parse(textBox5.Text)); while (true) { byte[] buf = client.Receive(ref endpoint); string msg = Encoding.Default.GetString(buf); textBox4.Text += msg + " "+ endpoint.Address.ToString() + " " + endpoint.Port + "---> "; } client.Close(); } private void button2_Click(object sender, EventArgs e) { //连续发送 timer1.Enabled = !timer1.Enabled; } private void button3_Click(object sender, EventArgs e) { //接受数据 按钮事件 Thread th = new Thread(new ThreadStart(RecvThread)); th.IsBackground = true; th.Start(); } } }
界面: