C#实现UDP广播
向255.255.255.255发送UPD数据包即为UDP广播,接收端只需绑定UDP广播的端口号即可得到数据
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Test
{
class Program
{
static void Main(string[] args)
{
UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Any, 0));
IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 7788);
byte[] buf = Encoding.Default.GetBytes("Hello from UDP broadcast");
Thread t = new Thread(new ThreadStart(RecvThread));
t.IsBackground = true;
t.Start();
while (true)
{
client.Send(buf, buf.Length, endpoint);
Thread.Sleep(1000);
}
}
static void RecvThread()
{
UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Any, 7788));
IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
byte[] buf = client.Receive(ref endpoint);
string msg = Encoding.Default.GetString(buf);
Console.WriteLine(msg);
}
}
}
}
本文由 创作,采用 知识共享署名4.0 国际许可协议进行许可。本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为: 2021/03/26 01:48