Question about SetSocketOption & MulticastOption
本文关键字:MulticastOption amp about SetSocketOption Question | 更新日期: 2023-09-27 17:59:32
我创建了一个组&在方法CCD_ 1通过创建线程等待消息之前1行发送消息。此代码完美地运行。我只是想知道,在我尝试向组发送内容之前,为什么不在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();
}
}
来自本文:
IP_ADD_MEMBERSHIP选项允许您要加入多播组由中的主机组地址指定多播地址结构。你必须加入组才能接收多播数据报您不需要加入组发送多播数据报
但是,由于默认的TTL值,这只能在本地子网上工作。请参阅本文以获得更明确的答案。