A UDP connection listener
Inheritance: ConnectionListenerBase
        public static void RunExample()
        {
            //Ensure we use the null serializer for unmanaged connections
            SendReceiveOptions options = new SendReceiveOptions<NullSerializer>();

            //Setup listening for incoming unmanaged UDP broadcasts
            UDPConnectionListener listener = new UDPConnectionListener(options, ApplicationLayerProtocolStatus.Disabled, UDPOptions.None);
            Connection.StartListening(listener, new IPEndPoint(IPAddress.Any, 10000));

            //Add a packet handler for unmanaged connections
            NetworkComms.AppendGlobalIncomingUnmanagedPacketHandler((packetHeader, connection, incomingBytes) => {
                Console.WriteLine("Received {0} bytes from {1}", incomingBytes.Length, connection.ConnectionInfo.RemoteEndPoint);
            });

            //Generate some test data to broadcast
            byte[] dataToSend = new byte[] { 1, 2,3, 4 };

            //Create an unmanaged packet manually and broadcast the test data
            //In future this part of the API could potentially be improved to make it clearer
            using(Packet sendPacket = new Packet("Unmanaged", dataToSend, options))
                UDPConnection.SendObject<byte[]>(sendPacket, new IPEndPoint(IPAddress.Broadcast, 10000), options, ApplicationLayerProtocolStatus.Disabled);

            Console.WriteLine("Client done!");
            Console.ReadKey();
        }
Exemple #2
0
        public static void StartListening(IPEndPoint newLocalEndPoint, bool useRandomPortFailOver = true, bool allowDiscoverable = false)
        {
            UDPConnectionListener listener = new UDPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, UDPConnection.DefaultUDPOptions, allowDiscoverable);

            Connection.StartListening(listener, newLocalEndPoint, useRandomPortFailOver);
        }
        /// <summary>
        /// Make this peer discoverable using the provided <see cref="DiscoveryMethod"/>. 
        /// IMPORTANT NOTE: For IP networks we strongly recommend using the UDP broadcast discovery method.
        /// </summary>
        /// <param name="discoveryMethod">The discovery method for which this peer should be discoverable</param>
        /// <param name="localDiscoveryEndPoint">The local endpoint with which to make this peer discoverable</param>
        public static void EnableDiscoverable(DiscoveryMethod discoveryMethod, EndPoint localDiscoveryEndPoint)
        {
#if !NETFX_CORE && !WINDOWS_PHONE
            if (discoveryMethod == DiscoveryMethod.UDPBroadcast || discoveryMethod == DiscoveryMethod.TCPPortScan)
#else
            if (discoveryMethod == DiscoveryMethod.UDPBroadcast)
#endif
            {
                lock (_syncRoot)
                {
                    if (_discoveryListeners.ContainsKey(discoveryMethod))
                        return;

                    if (!HostInfo.IP.FilteredLocalAddresses().Contains((localDiscoveryEndPoint as IPEndPoint).Address))
                        throw new ArgumentException("Provided endpoint must use a valid local address", "localDiscoveryEndPoint");

                    if ((localDiscoveryEndPoint as IPEndPoint).Port == 0)
                    {
                        IPAddress address = (localDiscoveryEndPoint as IPEndPoint).Address;

                        //Keep trying to listen on an ever increasing port number
                        for (int tryPort = MinTargetLocalIPPort; tryPort <= MaxTargetLocalIPPort; tryPort++)
                        {
                            try
                            {
                                ConnectionListenerBase listener;
                                if (discoveryMethod == DiscoveryMethod.UDPBroadcast)
                                    listener = new UDPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, UDPOptions.None, true);
                                else
                                    listener = new TCPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, true);

                                Connection.StartListening(listener, new IPEndPoint(address, tryPort));

                                //Once we are successfully listening we can break
                                _discoveryListeners.Add(discoveryMethod, new List<ConnectionListenerBase>() { listener });
                                break;
                            }
                            catch (Exception) { }

                            if (tryPort == MaxTargetLocalIPPort)
                                throw new CommsSetupShutdownException("Failed to find local available listen port on address " + address.ToString() + " while trying to make this peer discoverable. Consider increasing the available port range via MinTargetLocalIPPort and MaxTargetLocalIPPort.");
                        }
                    }
                    else
                    {
                        //Based on the connection type select all local endPoints and then enable discoverable
                        ConnectionListenerBase listener;
                        if (discoveryMethod == DiscoveryMethod.UDPBroadcast)
                            listener = new UDPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, UDPOptions.None, true);
                        else
                            listener = new TCPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, true);

                        Connection.StartListening(listener, localDiscoveryEndPoint);

                        //Once we are successfully listening we can break
                        _discoveryListeners.Add(discoveryMethod, new List<ConnectionListenerBase>() { listener });
                    }

                    //Add the packet handlers if required
                    foreach (var byMethodPair in _discoveryListeners)
                    {
                        foreach (ConnectionListenerBase listener in byMethodPair.Value)
                        {
                            if (!listener.IncomingPacketHandlerExists(discoveryPacketType, new NetworkComms.PacketHandlerCallBackDelegate<byte[]>(PeerDiscoveryHandler)))
                                listener.AppendIncomingPacketHandler<byte[]>(discoveryPacketType, PeerDiscoveryHandler);
                        }
                    }
                }
            }
#if NET35 || NET4
            else if (discoveryMethod == DiscoveryMethod.BluetoothSDP)
            {
                lock (_syncRoot)
                {
                    foreach (BluetoothRadio radio in BluetoothRadio.AllRadios)
                        if (radio.LocalAddress == (localDiscoveryEndPoint as BluetoothEndPoint).Address)
                            radio.Mode = RadioMode.Discoverable;

                    _discoveryListeners.Add(discoveryMethod, Connection.StartListening(ConnectionType.Bluetooth, localDiscoveryEndPoint, true));

                    //Add the packet handlers if required
                    foreach (var byMethodPair in _discoveryListeners)
                    {
                        foreach (ConnectionListenerBase listener in byMethodPair.Value)
                        {
                            if (!listener.IncomingPacketHandlerExists(discoveryPacketType, new NetworkComms.PacketHandlerCallBackDelegate<byte[]>(PeerDiscoveryHandler)))
                                listener.AppendIncomingPacketHandler<byte[]>(discoveryPacketType, PeerDiscoveryHandler);
                        }
                    }
                }
            }
#endif
            else
                throw new NotImplementedException("The requested discovery method has not been implemented on the current platform.");
        }
        /// <summary>
        /// Make this peer discoverable using the provided <see cref="DiscoveryMethod"/>. 
        /// Uses all suitable and allowed adaptors, e.g. for IP networks uses <see cref="HostInfo.IP.FilteredLocalAddresses()"/>.
        /// IMPORTANT NOTE: For IP networks we strongly recommend using the UDP broadcast discovery method.
        /// </summary>
        /// <param name="discoveryMethod"></param>
        public static void EnableDiscoverable(DiscoveryMethod discoveryMethod)
        {
            lock (_syncRoot)
            {
                if (_discoveryListeners.ContainsKey(discoveryMethod))
                    return;

                //Based on the connection type select all local endPoints and then enable discoverable
#if !NETFX_CORE && !WINDOWS_PHONE
                if (discoveryMethod == DiscoveryMethod.UDPBroadcast || discoveryMethod == DiscoveryMethod.TCPPortScan)
#else
                if (discoveryMethod == DiscoveryMethod.UDPBroadcast)
#endif
                {
                    //We should select one of the target points across all adaptors, no need for all adaptors to have
                    //selected a single uniform port which is what happens if we just pass IPAddress.Any to the StartListening method
                    List<IPAddress> localAddresses = new List<IPAddress>();

                    if (ListenMode == LocalListenMode.EachAdaptorIndependently || ListenMode == LocalListenMode.Both)
                        localAddresses.AddRange(HostInfo.IP.FilteredLocalAddresses());

                    if (ListenMode == LocalListenMode.OnlyZeroAdaptor || ListenMode == LocalListenMode.Both)
                        localAddresses.Add(IPAddress.Any);

                    List<ConnectionListenerBase> listeners = new List<ConnectionListenerBase>();
                    foreach (IPAddress address in localAddresses)
                    {
                        //Keep trying to listen on an ever increasing port number
                        for (int tryPort = MinTargetLocalIPPort; tryPort <= MaxTargetLocalIPPort; tryPort++)
                        {
                            try
                            {
                                ConnectionListenerBase listener;
                                if (discoveryMethod == DiscoveryMethod.UDPBroadcast)
                                    listener = new UDPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, UDPOptions.None, true);
                                else
                                    listener = new TCPConnectionListener(NetworkComms.DefaultSendReceiveOptions, ApplicationLayerProtocolStatus.Enabled, true);

                                Connection.StartListening(listener, new IPEndPoint(address, tryPort));

                                //Once we are successfully listening we can break
                                listeners.Add(listener);
                                break;
                            }
                            catch (Exception) { }

                            if (tryPort == MaxTargetLocalIPPort)
                                throw new CommsSetupShutdownException("Failed to find local available listen port on address " + address.ToString() + " while trying to make this peer discoverable. Consider increasing the available port range via MinTargetLocalIPPort and MaxTargetLocalIPPort.");
                        }
                    }

                    _discoveryListeners.Add(discoveryMethod, listeners);
                }
#if NET35 || NET4
                else if (discoveryMethod == DiscoveryMethod.BluetoothSDP)
                {
                    List<ConnectionListenerBase> listeners = new List<ConnectionListenerBase>();

                    foreach (BluetoothRadio radio in BluetoothRadio.AllRadios)
                    {
                        radio.Mode = RadioMode.Discoverable;
                        listeners.AddRange(Connection.StartListening(ConnectionType.Bluetooth, new BluetoothEndPoint(radio.LocalAddress, BluetoothDiscoveryService), true));
                    }
                    
                    _discoveryListeners.Add(discoveryMethod, listeners);
                }
#endif
                else
                    throw new NotImplementedException("The requested discovery method has not been implemented on the current platform.");
                
                //Add the packet handlers if required
                foreach (var byMethodPair in _discoveryListeners)
                {
                    foreach(ConnectionListenerBase listener in byMethodPair.Value)
                    {
                        if (!listener.IncomingPacketHandlerExists(discoveryPacketType, new NetworkComms.PacketHandlerCallBackDelegate<byte[]>(PeerDiscoveryHandler)))
                            listener.AppendIncomingPacketHandler<byte[]>(discoveryPacketType, PeerDiscoveryHandler);
                    }
                }
                    
            }
        }