关于SetSocketOption&的问题MulticastOption

时间:2011-06-20 16:05:16

标签: c# sockets multicast

我创建了一个小组&在方法Receive之前发送消息,通过创建线程等待消息。此代码适用于完美。我只是想知道为什么我不应该在Send方法中添加这一行,以便在我尝试向组发送内容之前将套接字加入组。

server.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, MulticastOption);

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

class MAIN
{
    private static MulticastOption CreateGroup()
    {
        return new MulticastOption(IPAddress.Parse("224.100.0.1"));
    }
    private static void Receive(MulticastOption MulticastOption)
    {
        Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
        EndPoint ep = (EndPoint)iep;
        sock.Bind(iep);
        sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, MulticastOption);
        //
        byte[] data = new byte[1024];
        new Thread(new ThreadStart(Send)).Start();
        int recv = sock.ReceiveFrom(data, ref ep);
        String stringData = Encoding.ASCII.GetString(data, 0, recv);
        Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString());
        sock.Close();
    }
    private static void Send()
    {
        Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        IPEndPoint iep = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050);


        byte[] data = Encoding.ASCII.GetBytes("This is a test message");
        server.SendTo(data, iep);
        server.Close();
    }
    public static void Main(String[] args)
    {
        Receive(CreateGroup());
        Console.ReadKey();
    }
}

1 个答案:

答案 0 :(得分:4)

来自this article

  

IP_ADD_MEMBERSHIP选项允许   您加入多播组   由主机组地址指定   多播地址结构。您   必须加入组才能接收组播   数据报。 您无需加入   组发送多播数据报。

但是,由于默认的TTL值,这仅适用于本地子网。有关更明确的答案,请参阅this article