说明

UDP组播。

组播使用

组播使用非常简单,

  1. 配置中启用广播UseBroadcast重要
  2. 在UdpSession启动后。调用JoinMulticastGroup即可加入组播。调用DropMulticastGroup,退出组播。

下列示例使用的是UdpPackageAdapter适配器,如果是普通udp接受端,请使用NormalUdpDataHandlingAdapter适配器。

  1. private static void TestUdpMulticastGroup()
  2. {
  3. IPEndPoint multicast = new IPEndPoint(IPAddress.Parse("224.5.6.7"), 7788);
  4. UdpSession mainUdpSession = new UdpSession();
  5. mainUdpSession.SetDataHandlingAdapter(new UdpPackageAdapter());
  6. //udpSession.SetDataHandlingAdapter(new NormalUdpDataHandlingAdapter());
  7. mainUdpSession.Setup(new RRQMConfig()
  8. .SetBindIPHost(new IPHost(7789))
  9. .SetThreadCount(1)
  10. .UseBroadcast()
  11. .SetBufferLength(1024 * 64))
  12. .Start();
  13. mainUdpSession.JoinMulticastGroup(IPAddress.Parse("224.5.6.7"));
  14. UdpSession multicastUdpSession = new UdpSession();
  15. multicastUdpSession.SetDataHandlingAdapter(new UdpPackageAdapter());
  16. //udpSession.SetDataHandlingAdapter(new NormalUdpDataHandlingAdapter());
  17. int count = 0;
  18. multicastUdpSession.Received += (remote, byteBlock, requestInfo) =>
  19. {
  20. Console.WriteLine(byteBlock.ToString());
  21. count++;
  22. if (count==5)
  23. {
  24. multicastUdpSession.DropMulticastGroup(IPAddress.Parse("224.5.6.7"));
  25. }
  26. };
  27. multicastUdpSession.Setup(new RRQMConfig()
  28. .SetBindIPHost(new IPHost(7788))
  29. .SetThreadCount(1)
  30. .SetBufferLength(1024 * 64))
  31. .Start();
  32. multicastUdpSession.JoinMulticastGroup(IPAddress.Parse("224.5.6.7"));
  33. while (true)
  34. {
  35. mainUdpSession.Send(multicast,Encoding.UTF8.GetBytes("RRQM"));
  36. Thread.Sleep(1000);
  37. }
  38. }

广播

广播的使用也非常简单,仅仅需要将发送的目的地址设置为255.255.255.255即可。此处可通过IPEndPoint实现,也可以通过IPHost实现。