Пример #1
0
        /// <summary>
        /// Create a connectionInfo object for a new connection.
        /// </summary>
        /// <param name="connectionType">The type of connection</param>
        /// <param name="remoteEndPoint">The remoteEndPoint of this connection</param>
        /// <param name="localEndPoint">The localEndpoint of this connection</param>
        /// <param name="applicationLayerProtocol">If enabled NetworkComms.Net uses a custom
        /// application layer protocol to provide useful features such as inline serialisation,
        /// transparent packet transmission, remote peer handshake and information etc. We strongly
        /// recommend you enable the NetworkComms.Net application layer protocol.</param>
        /// <param name="connectionListener">The listener associated with this connection if server side</param>
        internal ConnectionInfo(ConnectionType connectionType, EndPoint remoteEndPoint, EndPoint localEndPoint,
                                ApplicationLayerProtocolStatus applicationLayerProtocol = ApplicationLayerProtocolStatus.Enabled,
                                ConnectionListenerBase connectionListener = null)
        {
            if (localEndPoint == null)
            {
                throw new ArgumentNullException("localEndPoint", "localEndPoint may not be null");
            }

            if (remoteEndPoint == null)
            {
                throw new ArgumentNullException("remoteEndPoint", "remoteEndPoint may not be null");
            }

            if (applicationLayerProtocol == ApplicationLayerProtocolStatus.Undefined)
            {
                throw new ArgumentException("A value of ApplicationLayerProtocolStatus.Undefined is invalid when creating instance of ConnectionInfo.", "applicationLayerProtocol");
            }

            this.ServerSide               = (connectionListener != null);
            this.ConnectionListener       = connectionListener;
            this.ConnectionType           = connectionType;
            this.RemoteEndPoint           = remoteEndPoint;
            this.LocalEndPoint            = localEndPoint;
            this.ConnectionCreationTime   = DateTime.Now;
            this.ApplicationLayerProtocol = applicationLayerProtocol;
        }
Пример #2
0
        /// <summary>
        /// Create a new ConnectionInfo object pointing at the provided remote ipAddress and port.
        /// Provided ipAddress and port are parsed in to <see cref="RemoteEndPoint"/>.
        /// </summary>
        /// <param name="remoteIPAddress">IP address of the remote target in string format, e.g. "192.168.0.1"</param>
        /// <param name="remotePort">The available port of the remote target.
        /// Valid ports are 1 through 65535. Port numbers less than 256 are reserved for well-known services (like HTTP on port 80) and port numbers less than 1024 generally require admin access</param>
        /// <param name="applicationLayerProtocol">If enabled NetworkComms.Net uses a custom
        /// application layer protocol to provide useful features such as inline serialisation,
        /// transparent packet transmission, remote peer handshake and information etc. We strongly
        /// recommend you enable the NetworkComms.Net application layer protocol.</param>
        public ConnectionInfo(string remoteIPAddress, int remotePort, ApplicationLayerProtocolStatus applicationLayerProtocol)
        {
            if (applicationLayerProtocol == ApplicationLayerProtocolStatus.Undefined)
            {
                throw new ArgumentException("A value of ApplicationLayerProtocolStatus.Undefined is invalid when creating instance of ConnectionInfo.", "applicationLayerProtocol");
            }

            IPAddress ipAddress;

            if (!IPAddress.TryParse(remoteIPAddress, out ipAddress))
            {
                throw new ArgumentException("Provided remoteIPAddress string was not successfully parsed.", "remoteIPAddress");
            }

            this.RemoteEndPoint = new IPEndPoint(ipAddress, remotePort);

            switch (this.RemoteEndPoint.AddressFamily)
            {
            case AddressFamily.InterNetwork:
                this.LocalEndPoint = new IPEndPoint(IPAddress.Any, 0);
                break;

            case AddressFamily.InterNetworkV6:
                this.LocalEndPoint = new IPEndPoint(IPAddress.IPv6Any, 0);
                break;

            case (AddressFamily)32:
                this.LocalEndPoint = new BluetoothEndPoint(BluetoothAddress.None, BluetoothService.SerialPort);
                break;
            }

            this.ConnectionCreationTime   = DateTime.Now;
            this.ApplicationLayerProtocol = applicationLayerProtocol;
        }
Пример #3
0
        /// <summary>
        /// Create a new ConnectionInfo object pointing at the provided remote <see cref="IPEndPoint"/>
        /// </summary>
        /// <param name="remoteEndPoint">The end point corresponding with the remote target</param>
        /// <param name="applicationLayerProtocol">If enabled NetworkComms.Net uses a custom
        /// application layer protocol to provide useful features such as inline serialisation,
        /// transparent packet transmission, remote peer handshake and information etc. We strongly
        /// recommend you enable the NetworkComms.Net application layer protocol.</param>
        public ConnectionInfo(EndPoint remoteEndPoint, ApplicationLayerProtocolStatus applicationLayerProtocol)
        {
            if (applicationLayerProtocol == ApplicationLayerProtocolStatus.Undefined)
            {
                throw new ArgumentException("A value of ApplicationLayerProtocolStatus.Undefined is invalid when creating instance of ConnectionInfo.", "applicationLayerProtocol");
            }

            this.RemoteEndPoint = remoteEndPoint;

            switch (remoteEndPoint.AddressFamily)
            {
            case AddressFamily.InterNetwork:
                this.LocalEndPoint = new IPEndPoint(IPAddress.Any, 0);
                break;

            case AddressFamily.InterNetworkV6:
                this.LocalEndPoint = new IPEndPoint(IPAddress.IPv6Any, 0);
                break;

#if NET4 || NET35
            case (AddressFamily)32:
                this.LocalEndPoint = new BluetoothEndPoint(BluetoothAddress.None, BluetoothService.SerialPort);
                break;
#endif
            }

            this.ConnectionCreationTime   = DateTime.Now;
            this.ApplicationLayerProtocol = applicationLayerProtocol;
        }
Пример #4
0
        /// <summary>
        /// Create a connectionInfo object which can be used to inform a remote peer of local connectivity
        /// </summary>
        /// <param name="connectionType">The type of connection</param>
        /// <param name="localNetworkIdentifier">The local network identifier</param>
        /// <param name="localEndPoint">The localEndPoint which should be referenced remotely</param>
        /// <param name="isConnectable">True if connectable on provided localEndPoint</param>
        /// <param name="applicationLayerProtocol">If enabled NetworkComms.Net uses a custom
        /// application layer protocol to provide useful features such as inline serialisation,
        /// transparent packet transmission, remote peer handshake and information etc. We strongly
        /// recommend you enable the NetworkComms.Net application layer protocol.</param>
        public ConnectionInfo(ConnectionType connectionType, ShortGuid localNetworkIdentifier, EndPoint localEndPoint,
                              bool isConnectable, ApplicationLayerProtocolStatus applicationLayerProtocol)
        {
            if (localEndPoint == null)
            {
                throw new ArgumentNullException("localEndPoint", "localEndPoint may not be null");
            }

            if (applicationLayerProtocol == ApplicationLayerProtocolStatus.Undefined)
            {
                throw new ArgumentException("A value of ApplicationLayerProtocolStatus.Undefined is invalid when creating instance of ConnectionInfo.", "applicationLayerProtocol");
            }

            this.ConnectionType       = connectionType;
            this.NetworkIdentifierStr = localNetworkIdentifier.ToString();
            this.LocalEndPoint        = localEndPoint;

            switch (localEndPoint.AddressFamily)
            {
            case AddressFamily.InterNetwork:
                this.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                break;

            case AddressFamily.InterNetworkV6:
                this.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Any, 0);
                break;

            case (AddressFamily)32:
                this.RemoteEndPoint = new BluetoothEndPoint(BluetoothAddress.None, BluetoothService.SerialPort);
                break;
            }

            this.IsConnectable            = isConnectable;
            this.ApplicationLayerProtocol = applicationLayerProtocol;
        }
        /// <summary>
        /// Request user to provide server details and returns the result as a <see cref="ConnectionInfo"/> object. Performs the necessary validation and prevents code duplication across examples.
        /// </summary>
        /// <param name="applicationLayerProtocol">If enabled NetworkComms.Net uses a custom 
        /// application layer protocol to provide useful features such as inline serialisation, 
        /// transparent packet transmission, remote peer handshake and information etc. We strongly 
        /// recommend you enable the NetworkComms.Net application layer protocol.</param>
        public static ConnectionInfo GetServerDetails(ApplicationLayerProtocolStatus applicationLayerProtocol = ApplicationLayerProtocolStatus.Enabled)
        {
            if (lastServerIPEndPoint != null)
                Console.WriteLine("Please enter the destination IP and port. To reuse '{0}:{1}' use r:", lastServerIPEndPoint.Address, lastServerIPEndPoint.Port);
            else
                Console.WriteLine("Please enter the destination IP address and port, e.g. '192.168.0.1:10000':");

            while (true)
            {
                try
                {
                    //Parse the provided information
                    string userEnteredStr = Console.ReadLine();

                    if (userEnteredStr.Trim() == "r" && lastServerIPEndPoint != null)
                        break;
                    else
                    {
                        lastServerIPEndPoint = IPTools.ParseEndPointFromString(userEnteredStr);
                        break;
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("Unable to determine host IP address and port. Check format and try again:");
                }
            }

            return new ConnectionInfo(lastServerIPEndPoint, applicationLayerProtocol);
        }
        /// <summary>
        /// Create a new instance of a TCP listener
        /// </summary>
        /// <param name="sendReceiveOptions">The SendReceiveOptions to use with incoming data on this listener</param>
        /// <param name="applicationLayerProtocol">If enabled NetworkComms.Net uses a custom
        /// application layer protocol to provide useful features such as inline serialisation,
        /// transparent packet transmission, remote peer handshake and information etc. We strongly
        /// recommend you enable the NetworkComms.Net application layer protocol.</param>
        /// <param name="allowDiscoverable">Determines if the newly created <see cref="ConnectionListenerBase"/> will be discoverable if <see cref="Tools.PeerDiscovery"/> is enabled.</param>
        public TCPConnectionListener(SendReceiveOptions sendReceiveOptions,
                                     ApplicationLayerProtocolStatus applicationLayerProtocol, bool allowDiscoverable = false)
            : base(ConnectionType.TCP, sendReceiveOptions, applicationLayerProtocol, allowDiscoverable)
        {
#if !WINDOWS_PHONE && !NETFX_CORE
            SSLOptions = new SSLOptions();
#endif
        }
        /// <summary>
        /// Create a new instance of a UDP listener
        /// </summary>
        /// <param name="sendReceiveOptions">The SendReceiveOptions to use with incoming data on this listener</param>
        /// <param name="applicationLayerProtocol">If enabled NetworkComms.Net uses a custom 
        /// application layer protocol to provide useful features such as inline serialisation, 
        /// transparent packet transmission, remote peer handshake and information etc. We strongly 
        /// recommend you enable the NetworkComms.Net application layer protocol.</param>
        /// <param name="udpOptions">The UDPOptions to use with this listener</param>
        /// <param name="allowDiscoverable">Determines if the newly created <see cref="ConnectionListenerBase"/> will be discoverable if <see cref="Tools.PeerDiscovery"/> is enabled.</param>
        public UDPConnectionListener(SendReceiveOptions sendReceiveOptions,
            ApplicationLayerProtocolStatus applicationLayerProtocol, 
            UDPOptions udpOptions, bool allowDiscoverable = false)
            :base(ConnectionType.UDP, sendReceiveOptions, applicationLayerProtocol, allowDiscoverable)
        {
            if (applicationLayerProtocol == ApplicationLayerProtocolStatus.Disabled && udpOptions != UDPOptions.None)
                throw new ArgumentException("If the application layer protocol has been disabled the provided UDPOptions can only be UDPOptions.None.");

            UDPOptions = udpOptions;
        }
Пример #8
0
        /// <summary>
        /// Create a new instance of a UDP listener
        /// </summary>
        /// <param name="sendReceiveOptions">The SendReceiveOptions to use with incoming data on this listener</param>
        /// <param name="applicationLayerProtocol">If enabled NetworkComms.Net uses a custom
        /// application layer protocol to provide useful features such as inline serialisation,
        /// transparent packet transmission, remote peer handshake and information etc. We strongly
        /// recommend you enable the NetworkComms.Net application layer protocol.</param>
        /// <param name="udpOptions">The UDPOptions to use with this listener</param>
        /// <param name="allowDiscoverable">Determines if the newly created <see cref="ConnectionListenerBase"/> will be discoverable if <see cref="Tools.PeerDiscovery"/> is enabled.</param>
        public UDPConnectionListener(SendReceiveOptions sendReceiveOptions,
                                     ApplicationLayerProtocolStatus applicationLayerProtocol,
                                     UDPOptions udpOptions, bool allowDiscoverable = false)
            : base(ConnectionType.UDP, sendReceiveOptions, applicationLayerProtocol, allowDiscoverable)
        {
            if (applicationLayerProtocol == ApplicationLayerProtocolStatus.Disabled && udpOptions != UDPOptions.None)
            {
                throw new ArgumentException("If the application layer protocol has been disabled the provided UDPOptions can only be UDPOptions.None.");
            }

            UDPOptions = udpOptions;
        }
        /// <summary>
        /// Create a new listener instance
        /// </summary>
        /// <param name="connectionType">The connection type to listen for.</param>
        /// <param name="sendReceiveOptions">The send receive options to use for this listener</param>
        /// <param name="applicationLayerProtocol">If enabled NetworkComms.Net uses a custom
        /// application layer protocol to provide useful features such as inline serialisation,
        /// transparent packet transmission, remote peer handshake and information etc. We strongly
        /// recommend you enable the NetworkComms.Net application layer protocol.</param>
        /// <param name="allowDiscoverable">Determines if the newly created <see cref="ConnectionListenerBase"/> will be discoverable if <see cref="Tools.PeerDiscovery"/> is enabled.</param>
        protected ConnectionListenerBase(ConnectionType connectionType,
                                         SendReceiveOptions sendReceiveOptions,
                                         ApplicationLayerProtocolStatus applicationLayerProtocol,
                                         bool allowDiscoverable)
        {
            if (connectionType == ConnectionType.Undefined)
            {
                throw new ArgumentException("ConnectionType.Undefined is not valid when calling this method.", "connectionType");
            }
            if (sendReceiveOptions == null)
            {
                throw new ArgumentNullException("sendReceiveOptions", "Provided send receive option may not be null.");
            }
            if (applicationLayerProtocol == ApplicationLayerProtocolStatus.Undefined)
            {
                throw new ArgumentException("ApplicationLayerProtocolStatus.Undefined is not valid when calling this method.", "applicationLayerProtocol");
            }

            //Validate SRO options if the application layer protocol is disabled
            if (applicationLayerProtocol == ApplicationLayerProtocolStatus.Disabled)
            {
                if (sendReceiveOptions.Options.ContainsKey("ReceiveConfirmationRequired"))
                {
                    throw new ArgumentException("Attempted to create an unmanaged connection when the provided send receive" +
                                                " options specified the ReceiveConfirmationRequired option. Please provide compatible send receive options in order to successfully" +
                                                " instantiate this unmanaged connection.", "sendReceiveOptions");
                }

                if (sendReceiveOptions.DataSerializer != DPSManager.GetDataSerializer <NullSerializer>())
                {
                    throw new ArgumentException("Attempted to create an unmanaged connection when the provided send receive" +
                                                " options serialiser was not NullSerializer. Please provide compatible send receive options in order to successfully" +
                                                " instantiate this unmanaged connection.", "sendReceiveOptions");
                }

                if (sendReceiveOptions.DataProcessors.Count > 0)
                {
                    throw new ArgumentException("Attempted to create an unmanaged connection when the provided send receive" +
                                                " options contains data processors. Data processors may not be used with unmanaged connections." +
                                                " Please provide compatible send receive options in order to successfully instantiate this unmanaged connection.", "sendReceiveOptions");
                }
            }

            if (NetworkComms.LoggingEnabled)
            {
                NetworkComms.Logger.Info("Created new connection listener (" + connectionType.ToString() + "-" + (applicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled ? "E" : "D") + ").");
            }

            this.ConnectionType = connectionType;
            this.ListenerDefaultSendReceiveOptions = sendReceiveOptions;
            this.ApplicationLayerProtocol          = applicationLayerProtocol;
            this.IsDiscoverable = allowDiscoverable;
        }
Пример #10
0
        public ConnectionInfo GetServerDetails(ApplicationLayerProtocolStatus applicationLayerProtocol = ApplicationLayerProtocolStatus.Enabled)
        {
            string userEnteredStr = ServerIPAddress + ":" + ServerPort;

            try
            {
                lastServerIPEndPoint = IPTools.ParseEndPointFromString(userEnteredStr);
            }
            catch (Exception)
            {
                Log("Unable to determine host IP address and port. Check format and try again:", UTILITY);
            }

            return(new ConnectionInfo(lastServerIPEndPoint, applicationLayerProtocol));
        }
Пример #11
0
        /// <summary>
        /// Request user to provide server details and returns the result as a <see cref="ConnectionInfo"/> object. Performs the necessary validation and prevents code duplication across examples.
        /// </summary>
        /// <param name="applicationLayerProtocol">If enabled NetworkComms.Net uses a custom
        /// application layer protocol to provide useful features such as inline serialisation,
        /// transparent packet transmission, remote peer handshake and information etc. We strongly
        /// recommend you enable the NetworkComms.Net application layer protocol.</param>
        public static ConnectionInfo GetServerDetails(ApplicationLayerProtocolStatus applicationLayerProtocol = ApplicationLayerProtocolStatus.Enabled)
        {
            if (lastServerIPEndPoint != null)
            {
                Console.WriteLine("Please enter the destination IP and port. To reuse '{0}:{1}' use r:", lastServerIPEndPoint.Address, lastServerIPEndPoint.Port);
            }
            else
            {
                Console.WriteLine("Please enter the destination IP address and port, e.g. '192.168.0.1:10000':");
            }

            while (true)
            {
                try
                {
                    //Parse the provided information
                    string userEnteredStr = Console.ReadLine();

                    if (userEnteredStr.Trim() == "r" && lastServerIPEndPoint != null)
                    {
                        break;
                    }
                    else
                    {
                        lastServerIPEndPoint = IPTools.ParseEndPointFromString(userEnteredStr);
                        break;
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("Unable to determine host IP address and port. Check format and try again:");
                }
            }

            return(new ConnectionInfo(lastServerIPEndPoint, applicationLayerProtocol));
        }
Пример #12
0
        /// <summary>
        /// Sends a <see cref="Packet"/> to the provided endPoint. Offers more performance if an identical packet is being sent to multiple peers.
        /// NOTE: Any possible reply will be ignored unless listening for incoming UDP packets.
        /// </summary>
        /// <typeparam name="packetPayloadObjectType">The type of object encapsulated by the provided packet</typeparam>
        /// <param name="packetToSend">The packet to send</param>
        /// <param name="ipEndPoint">The destination IPEndPoint. Supports multicast endpoints.</param>
        /// <param name="sendReceiveOptions">The sendReceiveOptions to use for this send</param>
        /// <param name="applicationLayerProtocol">If enabled NetworkComms.Net uses a custom
        /// application layer protocol to provide useful features such as inline serialisation,
        /// transparent packet transmission, remote peer handshake and information etc. We strongly
        /// recommend you use the NetworkComms.Net application layer protocol.</param>
        public static void SendObject <packetPayloadObjectType>(IPacket packetToSend, IPEndPoint ipEndPoint, SendReceiveOptions sendReceiveOptions, ApplicationLayerProtocolStatus applicationLayerProtocol)
        {
            if (ipEndPoint == null)
            {
                throw new ArgumentNullException("ipEndPoint");
            }
            if (sendReceiveOptions == null)
            {
                throw new ArgumentNullException("sendReceiveOptions");
            }

            if (applicationLayerProtocol == ApplicationLayerProtocolStatus.Undefined)
            {
                throw new ArgumentException("A value of ApplicationLayerProtocolStatus.Undefined is invalid when using this method.", "applicationLayerProtocol");
            }

            if (sendReceiveOptions.Options.ContainsKey("ReceiveConfirmationRequired"))
            {
                throw new ArgumentException("Attempted to use a rouge UDP sender when the provided send receive" +
                                            " options specified the ReceiveConfirmationRequired option, which is unsupported. Please create a specific connection" +
                                            "instance to use this feature.", "sendReceiveOptions");
            }

            //Check the send receive options
            if (applicationLayerProtocol == ApplicationLayerProtocolStatus.Disabled)
            {
                if (sendReceiveOptions.DataSerializer != DPSManager.GetDataSerializer <NullSerializer>())
                {
                    throw new ArgumentException("Attempted to use a rouge UDP sender when the provided send receive" +
                                                " options serialiser was not NullSerializer. Please provide compatible send receive options in order to successfully" +
                                                " instantiate this unmanaged connection.", "sendReceiveOptions");
                }

                if (sendReceiveOptions.DataProcessors.Count > 0)
                {
                    throw new ArgumentException("Attempted to use a rouge UDP sender when the provided send receive" +
                                                " options contains data processors. Data processors may not be used with unmanaged connections." +
                                                " Please provide compatible send receive options in order to successfully instantiate this unmanaged connection.", "sendReceiveOptions");
                }
            }

            List <UDPConnection> connectionsToUse = null;

            //If we are already listening on what will be the outgoing adaptor we can send with that client to ensure reply packets are collected
            //The exception here is the broadcasting which goes out all adaptors
            if (ipEndPoint.Address != IPAddress.Broadcast)
            {
                #region Discover best local endpoint

                //Initialise best local end point as match all
                IPEndPoint bestLocalEndPoint = new IPEndPoint(IPAddress.Any, 0);
                try
                {
                    bestLocalEndPoint = IPTools.BestLocalEndPoint(ipEndPoint);
                    //Set the port to 0 to match all.
                    bestLocalEndPoint.Port = 0;
                }
                catch (SocketException ex)
                {
                    throw new ConnectionSetupException("Attempting to determine the best local endPoint to connect to " + ipEndPoint + " resulted in a socket exception.", ex);
                }
                catch (Exception ex)
                {
                    LogTools.LogException(ex, "BestLocalEndPointError", "Error while attempting to determine the best local end point to contact " + ipEndPoint.ToString());
                }

                #endregion Discover best local endpoint

                #region Check For Existing Local Listener

                List <UDPConnectionListener> existingListeners = Connection.ExistingLocalListeners <UDPConnectionListener>(bestLocalEndPoint);

                for (int i = 0; i < existingListeners.Count; i++)
                {
                    if (existingListeners[i].UDPConnection.ConnectionInfo.ApplicationLayerProtocol == applicationLayerProtocol)
                    {
                        connectionsToUse = new List <UDPConnection> {
                            existingListeners[i].UDPConnection
                        };

                        //Once we have a matching connection we can break
                        break;
                    }
                }

                #endregion Check For Existing Local Listener

                //If we have not picked up an existing listener we need to use/create a rougeSender
                if (connectionsToUse == null)
                {
                    #region Check For Suitable Rouge Sender

                    lock (udpRogueSenderCreationLocker)
                    {
                        if (NetworkComms.commsShutdown)
                        {
                            throw new CommunicationException("Attempting to send UDP packet but NetworkCommsDotNet is in the process of shutting down.");
                        }
                        else
                        {
                            if (!udpRogueSenders.ContainsKey(applicationLayerProtocol) ||
                                !udpRogueSenders[applicationLayerProtocol].ContainsKey(bestLocalEndPoint) ||
                                udpRogueSenders[applicationLayerProtocol][bestLocalEndPoint].ConnectionInfo.ConnectionState == ConnectionState.Shutdown)
                            {
                                //Create a new rogue sender
                                if (NetworkComms.LoggingEnabled)
                                {
                                    NetworkComms.Logger.Trace("Creating UDPRougeSender.");
                                }

                                if (!udpRogueSenders.ContainsKey(applicationLayerProtocol))
                                {
                                    udpRogueSenders.Add(applicationLayerProtocol, new Dictionary <IPEndPoint, UDPConnection>());
                                }

                                IPAddress anyRemoteIP = AnyRemoteIPAddress(ipEndPoint.AddressFamily);
                                udpRogueSenders[applicationLayerProtocol][bestLocalEndPoint] = new UDPConnection(new ConnectionInfo(ConnectionType.UDP, new IPEndPoint(anyRemoteIP, 0), bestLocalEndPoint, applicationLayerProtocol), sendReceiveOptions, UDPConnection.DefaultUDPOptions, false);
                            }

                            connectionsToUse = new List <UDPConnection> {
                                udpRogueSenders[applicationLayerProtocol][bestLocalEndPoint]
                            };
                        }
                    }

                    #endregion Check For Suitable Rouge Sender
                }
            }
            else
            {
                #region Get A Sender On All Interfaces For Broadcast

                lock (udpRogueSenderCreationLocker)
                {
                    //We do something special for broadcasts by selected EVERY adaptor
                    if (NetworkComms.LoggingEnabled)
                    {
                        NetworkComms.Logger.Trace("Getting senders for UDP broadcasting.");
                    }

                    if (!udpRogueSenders.ContainsKey(applicationLayerProtocol))
                    {
                        udpRogueSenders.Add(applicationLayerProtocol, new Dictionary <IPEndPoint, UDPConnection>());
                    }

                    connectionsToUse = new List <UDPConnection>();

                    //This is a broadcast and we need to send the broadcast over every local adaptor
                    List <IPAddress> validLocalIPAddresses = HostInfo.IP.FilteredLocalAddresses();
                    foreach (IPAddress address in validLocalIPAddresses)
                    {
                        IPEndPoint currentLocalIPEndPoint = new IPEndPoint(address, 0);
                        List <UDPConnectionListener> existingListeners = Connection.ExistingLocalListeners <UDPConnectionListener>(currentLocalIPEndPoint);

                        //If there is an existing listener we use that
                        if (existingListeners.Count > 0)
                        {
                            for (int i = 0; i < existingListeners.Count; i++)
                            {
                                if (existingListeners[i].UDPConnection.ConnectionInfo.ApplicationLayerProtocol == applicationLayerProtocol)
                                {
                                    connectionsToUse.Add(existingListeners[i].UDPConnection);

                                    //Once we have a matching connection we can break
                                    break;
                                }
                            }
                        }
                        else
                        {
                            //If not we check the rouge senders
                            if (!udpRogueSenders[applicationLayerProtocol].ContainsKey(currentLocalIPEndPoint) ||
                                udpRogueSenders[applicationLayerProtocol][currentLocalIPEndPoint].ConnectionInfo.ConnectionState == ConnectionState.Shutdown)
                            {
                                IPAddress anyRemoteIP = AnyRemoteIPAddress(currentLocalIPEndPoint.AddressFamily);

                                udpRogueSenders[applicationLayerProtocol][currentLocalIPEndPoint] = new UDPConnection(new ConnectionInfo(ConnectionType.UDP, new IPEndPoint(anyRemoteIP, 0), currentLocalIPEndPoint, applicationLayerProtocol), sendReceiveOptions, UDPConnection.DefaultUDPOptions, false);
                            }

                            connectionsToUse.Add(udpRogueSenders[applicationLayerProtocol][currentLocalIPEndPoint]);
                        }
                    }
                }

                #endregion Get A Sender On All Interfaces For Broadcast
            }

            foreach (UDPConnection connection in connectionsToUse)
            {
                try
                {
                    //This has been commented out for the time being as it made no difference to the broadcast issue
                    //we were investigating at the time we had issues
                    //Use the network broadcast address instead of the global broadcast address where possible
                    //if (ipEndPoint.Address == IPAddress.Broadcast && connection.ConnectionInfo.LocalIPEndPoint.AddressFamily == AddressFamily.InterNetwork)
                    //{
                    //    IPEndPoint ipEndPointToUse = new IPEndPoint(IPTools.GetIPv4NetworkBroadcastAddress(connection.ConnectionInfo.LocalIPEndPoint.Address), ipEndPoint.Port);
                    //    connection.SendPacketSpecific<packetPayloadObjectType>(packetToSend, ipEndPointToUse);
                    //}
                    //else
                    connection.SendPacketSpecific <packetPayloadObjectType>(packetToSend, ipEndPoint);
                }
                catch (SocketException) { /* Ignore any socket exceptions */ }
            }

            //Dispose of the packet
            packetToSend.Dispose();
        }
Пример #13
0
        /// <summary>
        /// Sends a single object to the provided endPoint. NOTE: Any possible reply will be ignored unless listening for incoming UDP packets.
        /// </summary>
        /// <param name="sendingPacketType">The sending packet type</param>
        /// <param name="objectToSend">The object to send</param>
        /// <param name="ipEndPoint">The destination IPEndPoint. Supports multicast endpoints.</param>
        /// <param name="sendReceiveOptions">The sendReceiveOptions to use for this send</param>
        /// <param name="applicationLayerProtocol">If enabled NetworkComms.Net uses a custom
        /// application layer protocol to provide useful features such as inline serialisation,
        /// transparent packet transmission, remote peer handshake and information etc. We strongly
        /// recommend you use the NetworkComms.Net application layer protocol.</param>
        public static void SendObject <sendObjectType>(string sendingPacketType, sendObjectType objectToSend, IPEndPoint ipEndPoint, SendReceiveOptions sendReceiveOptions, ApplicationLayerProtocolStatus applicationLayerProtocol)
        {
            Packet sendPacket = objectToSend as Packet;

            if (sendPacket == null)
            {
                sendPacket = new Packet(sendingPacketType, objectToSend, sendReceiveOptions);
            }
            else
            {
                if (sendPacket.PacketHeader.PacketType != sendingPacketType)
                {
                    throw new ArgumentException("Unable to send object of type Packet if the PacketHeader.PacketType and sendingPacketType do not match.");
                }
            }

            SendObject <sendObjectType>(sendPacket, ipEndPoint, sendReceiveOptions, applicationLayerProtocol);
        }
Пример #14
0
 /// <summary>
 /// Create a new instance of BluetoothConnectionListener
 /// </summary>
 /// <param name="sendReceiveOptions">The send receive options to use for this listener.</param>
 /// <param name="applicationLayerProtocol">If enabled NetworkComms.Net uses a custom
 /// application layer protocol to provide useful features such as inline serialisation,
 /// transparent packet transmission, remote peer handshake and information etc. We strongly
 /// recommend you enable the NetworkComms.Net application layer protocol.</param>
 /// <param name="allowDiscoverable">Determines if the newly created <see cref="ConnectionListenerBase"/> will be discoverable if <see cref="Tools.PeerDiscovery"/> is enabled.</param>
 public BluetoothConnectionListener(SendReceiveOptions sendReceiveOptions,
                                    ApplicationLayerProtocolStatus applicationLayerProtocol, bool allowDiscoverable = false)
     : base(ConnectionType.Bluetooth, sendReceiveOptions, applicationLayerProtocol, allowDiscoverable)
 {
 }
 /// <summary>
 /// Create a new instance of a TCP listener
 /// </summary>
 /// <param name="sendReceiveOptions">The SendReceiveOptions to use with incoming data on this listener</param>
 /// <param name="applicationLayerProtocol">If enabled NetworkComms.Net uses a custom
 /// application layer protocol to provide useful features such as inline serialisation,
 /// transparent packet transmission, remote peer handshake and information etc. We strongly
 /// recommend you enable the NetworkComms.Net application layer protocol.</param>
 /// <param name="sslOptions">The SSLOptions to use with this listener</param>
 /// <param name="allowDiscoverable">Determines if the newly created <see cref="ConnectionListenerBase"/> will be discoverable if <see cref="Tools.PeerDiscovery"/> is enabled.</param>
 public TCPConnectionListener(SendReceiveOptions sendReceiveOptions,
                              ApplicationLayerProtocolStatus applicationLayerProtocol, SSLOptions sslOptions, bool allowDiscoverable = false)
     : base(ConnectionType.TCP, sendReceiveOptions, applicationLayerProtocol, allowDiscoverable)
 {
     this.SSLOptions = sslOptions;
 }
Пример #16
0
        public void sendMessages(string peerMessage, string packetType)
        {
            string peerAddress = File.ReadLines("peerAddress.txt").First();


            //winViewer.peerReturn(out peerMessage, out peerAddress, out sendMessage, out exitCode);



            //Request a message to send somewhere
            //Console.WriteLine("\nPlease enter your message and press enter (Type 'exit' to quit):");
            //string stringToSend = Console.ReadLine();
            //Console.WriteLine("Message to send: " + propTest.peerMessage + " to " + propTest.peerAddress);
            //Console.WriteLine("Waiting...");

            string stringToSend = peerMessage;


            //Console.WriteLine("ready to send: " + stringToSend);

            //Console.WriteLine("exit");


            //If the user has typed exit then we leave our loop and end the example

            Console.WriteLine("Message to send: " + peerMessage + " to " + peerAddress);

            try
            {
                //Once we have a message we need to know where to send it
                //We have created a small wrapper class to help keep things clean here
                //ConnectionInfo targetServerConnectionInfo = ExampleHelper.GetServerDetails();
                IPEndPoint lastServerIPEndPoint = IPTools.ParseEndPointFromString(peerAddress);
                ApplicationLayerProtocolStatus applicationLayerProtocol = ApplicationLayerProtocolStatus.Enabled;
                ConnectionInfo targetServerConnectionInfo = new ConnectionInfo(lastServerIPEndPoint, applicationLayerProtocol);

                //We get a connection to the desired target server
                //This is performed using a static method, i.e. 'TCPConnection.GetConnection()' instead of
                //using 'new TCPConnection()' to ensure thread safety. This means if you have a multi threaded application
                //and attempt to get a connection the same target server simultaneously, you will only ever create
                //a single connection.
                Connection conn = TCPConnection.GetConnection(targetServerConnectionInfo);

                //We send the string using a 'Message' packet type
                //There are a large number of overrides to SendObject
                //Please see our other examples or the online API
                //http://www.networkcomms.net/api/
                //conn.SendObject("Message", stringToSend);
                conn.SendObject(packetType, stringToSend);
            }
            catch (CommsException ex)
            {
                //All NetworkComms.Net exception inherit from CommsException so we can easily
                //catch all just by catching CommsException. For the break down of exceptions please
                //see our online API.
                //http://www.networkcomms.net/api/

                //If an error occurs we need to decide what to do.
                //In this example we will just log to a file and continue.
                LogTools.LogException(ex, "IntermediateSendExampleError");
                Console.WriteLine("\nError: CommsException was caught. Please see the log file created for more information.\n");
            }
        }
        /// <summary>
        /// Create a new instance of BluetoothConnectionListener
        /// </summary>
        /// <param name="sendReceiveOptions">The send receive options to use for this listener.</param>
        /// <param name="applicationLayerProtocol">If enabled NetworkComms.Net uses a custom 
        /// application layer protocol to provide useful features such as inline serialisation, 
        /// transparent packet transmission, remote peer handshake and information etc. We strongly 
        /// recommend you enable the NetworkComms.Net application layer protocol.</param>
        /// <param name="allowDiscoverable">Determines if the newly created <see cref="ConnectionListenerBase"/> will be discoverable if <see cref="Tools.PeerDiscovery"/> is enabled.</param>
        public BluetoothConnectionListener(SendReceiveOptions sendReceiveOptions,
            ApplicationLayerProtocolStatus applicationLayerProtocol, bool allowDiscoverable = false)
            : base(ConnectionType.Bluetooth, sendReceiveOptions, applicationLayerProtocol, allowDiscoverable)
        {

        }