当前位置: 首页>>代码示例>>C#>>正文


C# UdpClient.JoinMulticastGroup方法代码示例

本文整理汇总了C#中System.Net.Sockets.UdpClient.JoinMulticastGroup方法的典型用法代码示例。如果您正苦于以下问题:C# UdpClient.JoinMulticastGroup方法的具体用法?C# UdpClient.JoinMulticastGroup怎么用?C# UdpClient.JoinMulticastGroup使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Sockets.UdpClient的用法示例。


在下文中一共展示了UdpClient.JoinMulticastGroup方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ServerContext

        public ServerContext(int port, int maxclients, ref List<string> TextStack, string OwnIP)
        {
            BeginSendUdpServerCallback = new AsyncCallback(OnBeginSendUdpServerCallbackFinished);
            ServerMessage = System.Text.Encoding.ASCII.GetBytes("OK:" + OwnIP);

            UdpServer = new UdpClient(new IPEndPoint(IPAddress.Any, 8011)); //da bei xp fehler

            UdpServer.JoinMulticastGroup(BroadcastServer.Address);

            UdpServer.BeginSend(ServerMessage, ServerMessage.Length, BroadcastServer, BeginSendUdpServerCallback, null);

            MaxClients = maxclients;

            Ip = IPAddress.Any;
            this.Port = port;

            listener = new TcpListener(Ip, Port);
            Clients = new List<ClientContext>(MaxClients);

            listener.Start();

            BeginAcceptSocketCallback = new AsyncCallback(OnClientConnected);

            this.TextStack = TextStack;
        }
开发者ID:janis2013,项目名称:TextVerteilerServerDns,代码行数:25,代码来源:ServerContext.cs

示例2: UDPMulticastProvider

        /* Methods */
        /// <summary>
        /// UDP multicast provider constructor
        /// </summary>
        /// <param name="lcm">LCM object</param>
        /// <param name="up">URL parser object</param>
        public UDPMulticastProvider(LCM lcm, URLParser up)
        {
            this.lcm = lcm;

            string[] addrport = up.Get("network", DEFAULT_NETWORK).Split(':');

            inetAddr = Dns.GetHostEntry(addrport[0]).AddressList[0];
            inetPort = Int32.Parse(addrport[1]);
            inetEP = new IPEndPoint(inetAddr, inetPort);

            sock = new UdpClient();
            sock.MulticastLoopback = true;
            sock.ExclusiveAddressUse = false;
            sock.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
            sock.Client.Bind(new IPEndPoint(IPAddress.Any, inetPort));

            int ttl = up.Get("ttl", DEFAULT_TTL);
            if (ttl == 0)
            {
                Console.Error.WriteLine("LCM: TTL set to zero, traffic will not leave localhost.");
            }
            else if (ttl > 1)
            {
                Console.Error.WriteLine("LCM: TTL set to > 1... That's almost never correct!");
            }
            else
            {
                Console.Error.WriteLine("LCM: TTL set to 1.");
            }
            sock.Ttl = (short) ttl;

            sock.JoinMulticastGroup(inetAddr);
        }
开发者ID:peddie,项目名称:conftron,代码行数:39,代码来源:UDPMulticastProvider.cs

示例3: ReaderAsync

        private static async Task ReaderAsync(int port, string groupAddress)
        {
            using (var client = new UdpClient(port))
            {
                if (groupAddress != null)
                {
                    client.JoinMulticastGroup(IPAddress.Parse(groupAddress));
                    WriteLine($"joining the multicast group {IPAddress.Parse(groupAddress)}");
                }

                bool completed = false;
                do
                {
                    WriteLine("starting the receiver");
                    UdpReceiveResult result = await client.ReceiveAsync();
                    byte[] datagram = result.Buffer;
                    string received = Encoding.UTF8.GetString(datagram);
                    WriteLine($"received {received}");
                    if (received == "bye")
                    {
                        completed = true;
                    }
                } while (!completed);
                WriteLine("receiver closing");

                if (groupAddress != null)
                {
                    client.DropMulticastGroup(IPAddress.Parse(groupAddress));
                }
            }
        }
开发者ID:ProfessionalCSharp,项目名称:ProfessionalCSharp6,代码行数:31,代码来源:Program.cs

示例4: BeginListeningAsync

		public async Task BeginListeningAsync (CancellationToken token)
		{
			var client = new UdpClient (BroadcastEndpoint);
			client.JoinMulticastGroup (BroadcastEndpoint.Address);
			token.Register (() => client.Close ());

			while (true) {
				token.ThrowIfCancellationRequested ();
				try {
					var result = await client.ReceiveAsync ();
					var data = Encoding.UTF8.GetString (result.Buffer);
					if (data.StartsWith (Header, StringComparison.Ordinal)) {
						if (ServerFound != null) {
							var details = new ServerDetails {
								Hostname = result.RemoteEndPoint.Address.ToString (),
								Port = int.Parse (data.Substring (Header.Length))
							};
							LoggingService.LogInfo ("Found TunezServer at {0}", details.FullAddress);
							ServerFound (this, details);
						}
					}
				} catch (ObjectDisposedException) {
					token.ThrowIfCancellationRequested ();
					throw;
				} catch (SocketException) {
					token.ThrowIfCancellationRequested ();
					// Ignore this
				} catch (Exception ex) {
					token.ThrowIfCancellationRequested ();
					LoggingService.LogInfo ("Ignoring bad UDP {0}", ex);
				}
			}
		}
开发者ID:alanmcgovern,项目名称:tunez,代码行数:33,代码来源:UdpBroadcast.cs

示例5: MulticastListen

 public void MulticastListen()
 {
     Console.WriteLine("Reciever Start");
     UdpClient receiveUdp = new UdpClient(this.port);
     try
     {
         receiveUdp.JoinMulticastGroup(this.multicastIP, 10);
     }
     catch (SocketException e)
     {
         Console.WriteLine(e.Message.ToString());
     }
     IPEndPoint remoteHost = null;
     while (true)
     {
         try
         {
             byte[] bytes = receiveUdp.Receive(ref remoteHost);
             string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
             Console.WriteLine(str);
         }
         catch
         {
             Console.WriteLine("Reciever Close");
             break;
         }
     }
 }
开发者ID:dalinhuang,项目名称:wdeqawes-efrwserd-rgtedrtf,代码行数:28,代码来源:Program.cs

示例6: BackgroundListener

        private void BackgroundListener()
        {
            IPEndPoint bindingEndpoint = new IPEndPoint(IPAddress.Any, _endPoint.Port);
            using (UdpClient client = new UdpClient())
            {
                client.ExclusiveAddressUse = false;
                client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                client.Client.Bind(bindingEndpoint);
                client.JoinMulticastGroup(_endPoint.Address);

                bool keepRunning = true;
                while (keepRunning)
                {
                    try
                    {
                        IPEndPoint remote = new IPEndPoint(IPAddress.Any, _endPoint.Port);
                        byte[] buffer = client.Receive(ref remote);
                        lock (this)
                        {
                            DataReceived(this, new MulticastDataReceivedEventArgs(remote, buffer));
                        }
                    }
                    catch (ThreadAbortException)
                    {
                        keepRunning = false;
                        Thread.ResetAbort();
                    }
                }

                client.DropMulticastGroup(_endPoint.Address);
            }
        }
开发者ID:Fuzzbawls,项目名称:MinerControl-KBomba,代码行数:32,代码来源:MulticastReceiver.cs

示例7: Start

        public bool Start()
        {
            try
            {
                //_logger.Debug(String.Format("Joining multicast group {0}:{1}", _multicastAddress, _port));

                _udpClient = new UdpClient();

                _udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                _udpClient.ExclusiveAddressUse = false;

                _endPoint = new IPEndPoint(IPAddress.Any, _port);
                _udpClient.Client.Bind(_endPoint);

                _udpClient.JoinMulticastGroup(IPAddress.Parse(_multicastAddress), IPAddress.Parse(_localAddress));

                //_logger.Debug(String.Format("\tJoined multicast group {0}:{1} successfully", _multicastAddress, _port));

                _isRunning = true;

                Receive();
            }
            catch (Exception ex)
            {
                //_logger.Error(String.Format("\tFailed to join multicast group {0}:{1}", _multicastAddress, _port), ex);
            }

            return _isRunning;
        }
开发者ID:dalevy,项目名称:DotNet-CyberThreatSimulator,代码行数:29,代码来源:ConsoleUdpListener.cs

示例8: Initialize

        public void Initialize()
        {
            tcpServer = new TcpListener(IPAddress.Any, 1901);

            tcpServer.BeginAcceptTcpClient()

            sender = new UdpClient();

            sender.DontFragment = true;

            sender.JoinMulticastGroup(remoteEndPoint.Address);

            listener = new UdpClient();

            listener.ExclusiveAddressUse = false;

            listener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

            listener.ExclusiveAddressUse = false;

            listener.Client.Bind(anyEndPoint);

            listener.DontFragment = true;

            listener.JoinMulticastGroup(remoteEndPoint.Address);

            listener.BeginReceive(ReceiveCallback, null);
        }
开发者ID:DisruptionTheory,项目名称:Iris,代码行数:28,代码来源:IrisNetworkManager.cs

示例9: Connect

        /// <summary>
        ///     Start the connection
        /// </summary>
        public override void Connect()
        {
            try
            {
                IEnumerable<IPAddress> ipv4Addresses =
                    Dns
                        .GetHostAddresses(Dns.GetHostName())
                        .Where(i => i.AddressFamily == AddressFamily.InterNetwork);

                foreach (IPAddress localIp in ipv4Addresses)
                {
                    var client = new UdpClient(new IPEndPoint(localIp, _localEndpoint.Port));
                    _udpClients.Add(client);
                    client.JoinMulticastGroup(ConnectionConfiguration.IpAddress, localIp);
                }
            }
            catch (SocketException ex)
            {
                throw new ConnectionErrorException(ConnectionConfiguration, ex);
            }

            // TODO: Maybe if we have a base Connect helper which takes in a KnxReceiver and KnxSender,
            // we can make the property setters more restricted
            KnxReceiver = new KnxReceiverRouting(this, _udpClients);
            KnxReceiver.Start();

            KnxSender = new KnxSenderRouting(this, _udpClients, RemoteEndpoint);

            Connected();
        }
开发者ID:CumpsD,项目名称:knx.net,代码行数:33,代码来源:KnxConnectionRouting.cs

示例10: HandleBroadcasts

        private void HandleBroadcasts()
        {
            var localIP = new IPEndPoint(IPAddress.Any, 50001);
            var udpClient = new UdpClient();
            udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            udpClient.ExclusiveAddressUse = false;
            udpClient.Client.Bind(localIP);

            var multicastingIP = IPAddress.Parse("228.5.6.7");
            udpClient.JoinMulticastGroup(multicastingIP);

            running = true;
            while (running)
            {
                var bytes = udpClient.Receive(ref localIP);
                var message = Encoding.UTF8.GetString(bytes);

                Dispatcher.Invoke(() =>
                {
                    lblResponse.Content = message;
                });
            }

            udpClient.DropMulticastGroup(multicastingIP);
            udpClient.Close();
        }
开发者ID:bdr27,项目名称:c-,代码行数:26,代码来源:MainWindow.xaml.cs

示例11: SearchSniffer

        public SearchSniffer()
        {
            IPAddress[] LocalAddresses = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
            ArrayList temp = new ArrayList();
            foreach (IPAddress i in LocalAddresses) temp.Add(i);
            temp.Add(IPAddress.Loopback);
            LocalAddresses = (IPAddress[])temp.ToArray(typeof(IPAddress));

            for (int id = 0; id < LocalAddresses.Length; ++id)
            {
                try
                {
                    var localEndPoint = new IPEndPoint(LocalAddresses[id], 1900);
                    UdpClient ssdpSession = new UdpClient(localEndPoint);
                    ssdpSession.MulticastLoopback = false;
                    ssdpSession.EnableBroadcast = true;
                    if (localEndPoint.AddressFamily == AddressFamily.InterNetwork)
                    {
                        ssdpSession.JoinMulticastGroup(UpnpMulticastV4Addr, LocalAddresses[id]);
                    }

                    uint IOC_IN = 0x80000000;
                    uint IOC_VENDOR = 0x18000000;
                    uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
                    ssdpSession.Client.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);

                    ssdpSession.BeginReceive(new AsyncCallback(OnReceiveSink), new object[] { ssdpSession, localEndPoint });
                    SSDPSessions[ssdpSession] = ssdpSession;
                }
                catch (Exception) { }
            }
        }
开发者ID:RyanMelenaNoesis,项目名称:ElveVenstarColorTouchDriver,代码行数:32,代码来源:SearchSniffer.cs

示例12: Start

        public void Start()
        {
            var version = ServiceType.Assembly.GetName().Version;
            var versionStr = version.Major + "." + version.Minor;
            var ssdpMsg = Encoding.UTF8.GetBytes(string.Format(SSDP_FORMAT, ServiceType.Name, versionStr, ServerName, Port));

            UdpClient udp = new UdpClient();
            udp.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            udp.Client.Bind(new IPEndPoint(IPAddress.Any, Port));
            udp.JoinMulticastGroup(SSDP_ENDPOINT.Address);

            IsStopped = false;
            var thread = new Thread(() =>
            {
                try
                {
                    while (!IsStopped)
                    {
                        udp.Send(ssdpMsg, ssdpMsg.Length, SSDP_ENDPOINT);
                        Thread.Sleep(Interval);
                    }
                }
                catch
                { }
                finally
                {
                    try { udp.Close(); }
                    catch { }
                }
            });
            thread.IsBackground = true;
            thread.Start();
        }
开发者ID:wan-qy,项目名称:CenaPlus,代码行数:33,代码来源:ServiceBroadcaster.cs

示例13: ProsthesisTelemetryReceiver

 public ProsthesisTelemetryReceiver(Logger logger)
 {
     mLogger = logger;
     mUDPReceiver = new UdpClient(ProsthesisCore.ProsthesisConstants.kTelemetryPort);
     mUDPReceiver.JoinMulticastGroup(IPAddress.Parse(ProsthesisCore.ProsthesisConstants.kMulticastGroupAddress));
     mTelemetryReceiver = new System.Threading.Thread(RunThread);
 }
开发者ID:gjorban,项目名称:ProsthesisPi,代码行数:7,代码来源:ProsthesisTelemetryReceiver.cs

示例14: Chat

 public Chat()
 {
     _multicastAddress = IPAddress.Parse("239.0.0.222");
     _udpClient = new UdpClient();
     _udpClient.JoinMulticastGroup(_multicastAddress);
     _remoteEp = new IPEndPoint(_multicastAddress, 2222);
 }
开发者ID:Kokokos,项目名称:kokochat,代码行数:7,代码来源:Chat.cs

示例15: Networking_UDPMultiOut

        public Networking_UDPMultiOut(int port)
        {
            client = new UdpClient();

            IPAddress multicastaddress = IPAddress.Parse("238.0.0.222");
            client.JoinMulticastGroup(multicastaddress);
            remoteep = new IPEndPoint(multicastaddress, port);
        }
开发者ID:valdemart,项目名称:Motorki,代码行数:8,代码来源:Networking_UDPMulti.cs


注:本文中的System.Net.Sockets.UdpClient.JoinMulticastGroup方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。