C# 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(5566);
            client.JoinMulticastGroup(IPAddress.Parse("234.5.6.7"));
            IPEndPoint multicast = new IPEndPoint(IPAddress.Parse("234.5.6.7"), 7788);
            byte[] buf = Encoding.Default.GetBytes("Hello from multicast");
            Thread t = new Thread(new ThreadStart(RecvThread));
            t.IsBackground = true;
            t.Start();
            while (true)
            {
                client.Send(buf, buf.Length, multicast);
                Thread.Sleep(1000);
            }
        }

        static void RecvThread()
        {
            UdpClient client = new UdpClient(7788);
            client.JoinMulticastGroup(IPAddress.Parse("234.5.6.7"));
            IPEndPoint multicast = new IPEndPoint(IPAddress.Parse("234.5.6.7"), 5566);
            while (true)
            {
                byte[] buf = client.Receive(ref multicast);
                string msg = Encoding.Default.GetString(buf);
                Console.WriteLine(msg);
            }
        }
    }
}

组播地址为 224.0.0.0 ~ 239.255.255.255,其中 224.0.0.0~224.255.255.255 不建议在用户程序中使用,因为它们一般都有特殊用途。

 

//广播代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
           
Socket socket = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.IP);//只能用 P协议发送广播,所以ProtocolType设置为 P

            IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 10881);                              //让其自动提供子网中的IP地址
           
socket.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.Broadcast, 1);          //设置broadcast值为1,允许套接字发送广播信息

            Int32  i = 0;
            while (true)
            {
                Thread.Sleep(1000);
                string info = "Hello";
                byte[] bInfo = Encoding.UTF8.GetBytes(info);
                socket.SendTo(bInfo, iep);
            }
        }
    }

}



此条目发表在network分类目录,贴了, 标签。将固定链接加入收藏夹。