public static void RunExample()
        {
            Console.WriteLine("Please select thrower or catcher mode:");
            Console.WriteLine("1 - Thrower Mode (Sends data)");
            Console.WriteLine("2 - Catcher Mode (Listens for data)");

            //Read in user choice
            if (Console.ReadKey(true).Key == ConsoleKey.D1)
            {
                throwerMode = true;
            }
            else
            {
                throwerMode = false;
            }

            if (throwerMode)
            {
                var nullCompressionSRO = new SendReceiveOptions(DPSManager.GetDataSerializer <ProtobufSerializer>(),
                                                                new List <DataProcessor>(),
                                                                new Dictionary <string, string>());

                //IPEndPoint catcherPoint = new IPEndPoint(IPAddress.Parse("131.111.73.200"), 10000);
                IPEndPoint catcherPoint = new IPEndPoint(IPAddress.Parse("172.24.252.32"), 10000);
                byte[]     throwData    = new byte[20 * 1024 * 1024];
                //byte[] throwData = new byte[1024 * 50];
                new Random().NextBytes(throwData);

                Task.Factory.StartNew(() =>
                {
                    while (true)
                    {
                        TCPConnection.GetConnection(new ConnectionInfo(catcherPoint)).SendObject("ThrowData", throwData, nullCompressionSRO);
                    }
                });

                Console.WriteLine("Let the throwing begin!\n");

                while (true)
                {
                    Console.WriteLine("IN - {0} - Instance Load = {1}, 5 sec load= {2}, 15 sec load= {3}", DateTime.Now.ToLongTimeString(), HostInfo.IP.CurrentNetworkLoadIncoming.ToString("0.000"), HostInfo.IP.AverageNetworkLoadIncoming(5).ToString("0.000"), HostInfo.IP.AverageNetworkLoadIncoming(15).ToString("0.000"));
                    Console.WriteLine("OUT - {0} - Instance Load = {1}, 5 sec load= {2}, 15 sec load= {3}", DateTime.Now.ToLongTimeString(), HostInfo.IP.CurrentNetworkLoadOutgoing.ToString("0.000"), HostInfo.IP.AverageNetworkLoadOutgoing(5).ToString("0.000"), HostInfo.IP.AverageNetworkLoadOutgoing(15).ToString("0.000"));
                    Thread.Sleep(1000);
                }
            }
            else
            {
                NetworkComms.AppendGlobalIncomingPacketHandler <byte[]>("ThrowData", (packetHeader, connection, data) =>
                {
                    Console.WriteLine("{0} - Caught {1} bytes thrown by {2}.", DateTime.Now.ToLongTimeString(), data.Length, connection.ConnectionInfo);
                });

                //Start listening for TCP connections
                //We want to select a random port on all available adaptors so provide
                //an IPEndPoint using IPAddress.Any and port 0.
                Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Any, 0));

                Console.WriteLine("Let the catching begin, on port " + ((IPEndPoint)Connection.ExistingLocalListenEndPoints(ConnectionType.TCP).First()).Port + "!\n");
                while (true)
                {
                    Console.WriteLine("IN - {0} - Instance Load = {1}, 5 sec load= {2}, 15 sec load= {3}", DateTime.Now.ToLongTimeString(), HostInfo.IP.CurrentNetworkLoadIncoming.ToString("0.000"), HostInfo.IP.AverageNetworkLoadIncoming(5).ToString("0.000"), HostInfo.IP.AverageNetworkLoadIncoming(15).ToString("0.000"));
                    Console.WriteLine("OUT - {0} - Instance Load = {1}, 5 sec load= {2}, 15 sec load= {3}", DateTime.Now.ToLongTimeString(), HostInfo.IP.CurrentNetworkLoadOutgoing.ToString("0.000"), HostInfo.IP.AverageNetworkLoadOutgoing(5).ToString("0.000"), HostInfo.IP.AverageNetworkLoadOutgoing(15).ToString("0.000"));
                    Thread.Sleep(10000);
                }
            }
        }
示例#2
0
        /// <summary>
        /// Run example
        /// </summary>
        public static void RunExample()
        {
            SendReceiveOptions nullCompressionSRO = new SendReceiveOptions(DPSManager.GetDataSerializer <ProtobufSerializer>(), null, null);

            NetworkComms.DefaultSendReceiveOptions = nullCompressionSRO;

            //We need to define what happens when packets are received.
            //To do this we add an incoming packet handler for a 'Message' packet type.
            //
            //We will define what we want the handler to do inline by using a lambda expression
            //http://msdn.microsoft.com/en-us/library/bb397687.aspx.
            //We could also just point the AppendGlobalIncomingPacketHandler method
            //to a standard method (See AdvancedSend example)
            //
            //This handler will convert the incoming raw bytes into a string (this is what
            //the <string> bit means) and then write that string to the local console window.
            NetworkComms.AppendGlobalIncomingPacketHandler <PingRequestReturnDC>("Message", (packetHeader, connection, incomingString) => { Console.WriteLine("\n  ... Incoming message from " + connection.ToString() + " saying '" + incomingString.ClientID + "'-'" + incomingString.PingID + "'."); });

            //Start listening for incoming 'TCP' connections.
            //We want to select a random port on all available adaptors so provide
            //an IPEndPoint using IPAddress.Any and port 0.
            //See also UDPConnection.StartListening()
            Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Any, 0));

            //Print the IP addresses and ports we are listening on to make sure everything
            //worked as expected.
            Console.WriteLine("Listening for messages on:");
            foreach (System.Net.IPEndPoint localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP))
            {
                Console.WriteLine("{0}:{1}", localEndPoint.Address, localEndPoint.Port);
            }

            //We loop here to allow any number of test messages to be sent and received
            while (true)
            {
                //Request a message to send somewhere
                Console.WriteLine("\nPlease enter your message and press enter (Type 'exit' to quit):");
                string stringToSend = Console.ReadLine();

                //If the user has typed exit then we leave our loop and end the example
                if (stringToSend == "exit")
                {
                    break;
                }
                else
                {
                    //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(out targetServerConnectionInfo);

                    PingRequestReturnDC test = new PingRequestReturnDC(0, 0);

                    //There are loads of ways of sending data (see AdvancedSend example for more)
                    //but the most simple, which we use here, just uses an IP address (string) and port (integer)
                    //We pull these values out of the ConnectionInfo object we got above and voila!
                    NetworkComms.SendObject("Message", ((System.Net.IPEndPoint)targetServerConnectionInfo.RemoteEndPoint).Address.ToString(), ((System.Net.IPEndPoint)targetServerConnectionInfo.RemoteEndPoint).Port, test);
                }
            }

            //We should always call shutdown on comms if we have used it
            NetworkComms.Shutdown();
        }
示例#3
0
        /// <summary>
        /// 获取protobuf serializer
        /// </summary>
        /// <returns></returns>
        public static DataSerializer GetProtobufSerializer()
        {
            DataSerializer serializer = DPSManager.GetDataSerializer <ProtobufSerializer>();

            return(serializer);
        }
        /// <summary>
        /// Append a listener specific packet handler
        /// </summary>
        /// <typeparam name="incomingObjectType">The type of incoming object</typeparam>
        /// <param name="packetTypeStr">The packet type for which this handler will be executed</param>
        /// <param name="packetHandlerDelgatePointer">The delegate to be executed when a packet of packetTypeStr is received</param>
        /// <param name="options">The <see cref="SendReceiveOptions"/> to be used for the provided packet type</param>
        public void AppendIncomingPacketHandler <incomingObjectType>(string packetTypeStr, NetworkComms.PacketHandlerCallBackDelegate <incomingObjectType> packetHandlerDelgatePointer, SendReceiveOptions options)
        {
            if (packetTypeStr == null)
            {
                throw new ArgumentNullException("packetTypeStr", "Provided packetType string cannot be null.");
            }
            if (packetHandlerDelgatePointer == null)
            {
                throw new ArgumentNullException("packetHandlerDelgatePointer", "Provided NetworkComms.PacketHandlerCallBackDelegate<incomingObjectType> cannot be null.");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options", "Provided SendReceiveOptions cannot be null.");
            }

            //If we are adding a handler for an unmanaged packet type the data serializer must be NullSerializer
            //Checks for unmanaged packet types
            if (packetTypeStr == Enum.GetName(typeof(ReservedPacketType), ReservedPacketType.Unmanaged))
            {
                if (options.DataSerializer != DPSManager.GetDataSerializer <NullSerializer>())
                {
                    throw new ArgumentException("Attempted to add packet handler for an unmanaged packet type when the provided send receive options serializer was not NullSerializer.");
                }

                if (options.DataProcessors.Count > 0)
                {
                    throw new ArgumentException("Attempted to add packet handler for an unmanaged packet type when the provided send receive options contains data processors. Data processors may not be used inline with unmanaged packet types.");
                }
            }

            lock (delegateLocker)
            {
                if (incomingPacketUnwrappers.ContainsKey(packetTypeStr))
                {
                    //Make sure if we already have an existing entry that it matches with the provided
                    if (!incomingPacketUnwrappers[packetTypeStr].Options.OptionsCompatible(options))
                    {
                        throw new PacketHandlerException("The provided SendReceiveOptions are not compatible with existing SendReceiveOptions already specified for this packetTypeStr.");
                    }
                }
                else
                {
                    incomingPacketUnwrappers.Add(packetTypeStr, new PacketTypeUnwrapper(packetTypeStr, options));
                }

                //Ad the handler to the list
                if (incomingPacketHandlers.ContainsKey(packetTypeStr))
                {
                    //Make sure we avoid duplicates
                    PacketTypeHandlerDelegateWrapper <incomingObjectType> toCompareDelegate = new PacketTypeHandlerDelegateWrapper <incomingObjectType>(packetHandlerDelgatePointer);
                    bool delegateAlreadyExists = false;
                    foreach (var handler in incomingPacketHandlers[packetTypeStr])
                    {
                        if (handler == toCompareDelegate)
                        {
                            delegateAlreadyExists = true;
                            break;
                        }
                    }

                    if (delegateAlreadyExists)
                    {
                        throw new PacketHandlerException("This specific packet handler delegate already exists for the provided packetTypeStr.");
                    }

                    incomingPacketHandlers[packetTypeStr].Add(new PacketTypeHandlerDelegateWrapper <incomingObjectType>(packetHandlerDelgatePointer));
                }
                else
                {
                    incomingPacketHandlers.Add(packetTypeStr, new List <IPacketTypeHandlerDelegateWrapper>()
                    {
                        new PacketTypeHandlerDelegateWrapper <incomingObjectType>(packetHandlerDelgatePointer)
                    });
                }

                if (NetworkComms.LoggingEnabled)
                {
                    NetworkComms.Logger.Info("Added listener specific incoming packetHandler for '" + packetTypeStr + "' packetType on listener " + ToString());
                }
            }
        }
        static void Main(string[] args)
        {
            TStuffLog.LogLevel     = LogLevel.Info;
            TStuffLog.LogFileLevel = LogLevel.Info;
            TStuffLog.LogActions.Add((message, serializedObject, level, member, filepat, line) =>
            {
                if (TStuffLog.LogLevel > level)
                {
                    return;
                }
                switch (level)
                {
                case LogLevel.Trace:
                    Console.ForegroundColor = ConsoleColor.Green;
                    break;

                case LogLevel.Debug:
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    break;

                case LogLevel.Info:

                    break;

                case LogLevel.Warning:
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    break;

                case LogLevel.Error:
                case LogLevel.Fatal:
                    Console.ForegroundColor = ConsoleColor.Red;
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(level), level, null);
                }
                Console.WriteLine("[{5},{0}/{1}:{2}, Level:{3}] Message: {4}", filepat.Split('\\').Last(), member, line, level.ToString(), message, DateTime.Now.ToString("T"));
                Console.ResetColor();
            });

            NetworkComms.DisableLogging();

            if (File.Exists("config.json"))
            {
                GConfig.D = JsonConvert.DeserializeObject <GameServerConfiguration>(File.ReadAllText("config.json"));
            }
            else
            {
                GConfig.D = new GameServerConfiguration();
                File.WriteAllText("config.json", JsonConvert.SerializeObject(GConfig.D, Formatting.Indented));
            }
            TStuffLog.Info("Server Started");
            TStuffLog.LogLevel     = GConfig.D.ServerLogLevel;
            TStuffLog.LogFileLevel = GConfig.D.LogFileLevel;

            DataSerializer ds = DPSManager.GetDataSerializer <ProtobufSerializer>();

            NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions(ds, new List <DataProcessor>(), new Dictionary <string, string>());
            var gamecontext = SetupGameRegister();

            SetupGlobalNetworkHandler(gamecontext);

            GConfig.D.GameSimulationTime = 400;
            var cont = new LoginService(gamecontext);
            var map  = new CreateGameService(gamecontext);


            Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Any, GConfig.D.ServerPort));
            //Connectc fake user
            gamecontext.User.AddSystemUser(GConfig.D.MainBotName + " 0", 0);
            gamecontext.User.AddSystemUser(GConfig.D.MainBotName + " 1", 1);
            gamecontext.User.AddSystemUser(GConfig.D.MainBotName + " 2", 2);
            gamecontext.User.AddSystemUser(GConfig.D.MainBotName + " 3", 3);
            gamecontext.User.AddSystemUser(GConfig.D.MainBotName + " 4", 4);


            //File.WriteAllText("mobs.json",JsonConvert.SerializeObject(gamecontext.Mobs));
            //File.WriteAllText("tower.json", JsonConvert.SerializeObject(gamecontext.Towers));
            //File.WriteAllText("race_mob.json", JsonConvert.SerializeObject(gamecontext.MobRaces));
            //File.WriteAllText("race_tower.json", JsonConvert.SerializeObject(gamecontext.TowerRaces));

            Console.ReadLine();
        }
        /// <summary>
        /// Run example
        /// </summary>
        public static void RunExample()
        {
            NetworkComms.ConnectionEstablishTimeoutMS = int.MaxValue;

            SendReceiveOptions nullCompressionSRO = new SendReceiveOptions(DPSManager.GetDataSerializer <ProtobufSerializer>(), null, null);

            NetworkComms.DefaultSendReceiveOptions = nullCompressionSRO;

            //We need to define what happens when packets are received.
            //To do this we add an incoming packet handler for a 'Message' packet type.
            //
            //We will define what we want the handler to do inline by using a lambda expression
            //http://msdn.microsoft.com/en-us/library/bb397687.aspx.
            //We could also just point the AppendGlobalIncomingPacketHandler method
            //to a standard method (See AdvancedSend example)
            //
            //This handler will convert the incoming raw bytes into a string (this is what
            //the <string> bit means) and then write that string to the local console window.
            NetworkComms.AppendGlobalIncomingPacketHandler <string>("Message", (packetHeader, connection, incomingString) => { Console.WriteLine("\n  ... Incoming message from " + connection.ToString() + " saying '" + incomingString + "'."); });

            //Start listenning
            BluetoothRadio defaultRadio = BluetoothRadio.PrimaryRadio;

            defaultRadio.Mode = RadioMode.Discoverable;
            Connection.StartListening(ConnectionType.Bluetooth, new BluetoothEndPoint(defaultRadio.LocalAddress, ServiceGUID), true);

            //Print the address we are listening on to make sure everything
            //worked as expected.
            Console.WriteLine("Listening for messages on:");
            foreach (var localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.Bluetooth))
            {
                Console.WriteLine("{0}", localEndPoint);
            }

            PeerDiscovery.EnableDiscoverable(PeerDiscovery.DiscoveryMethod.BluetoothSDP);

            //We loop here to allow any number of test messages to be sent and received
            while (true)
            {
                //Request a message to send somewhere
                Console.WriteLine("\nPlease enter your message and press enter (Type 'exit' to quit):");
                string stringToSend = Console.ReadLine();

                //If the user has typed exit then we leave our loop and end the example
                if (stringToSend == "exit")
                {
                    break;
                }
                else
                {
                    //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
                    var endpoints = PeerDiscovery.DiscoverPeers(PeerDiscovery.DiscoveryMethod.BluetoothSDP, 1000);

                    ConnectionInfo targetServerConnectionInfo = new ConnectionInfo(new BluetoothEndPoint(new BluetoothAddress(0xE0B9A5FB552BL), ServiceGUID));

                    //There are loads of ways of sending data (see AdvancedSend example for more)
                    //but the most simple, which we use here, just uses an IP address (string) and port (integer)
                    //We pull these values out of the ConnectionInfo object we got above and voila!
                    var connection = BluetoothConnection.GetConnection(targetServerConnectionInfo);

                    connection.SendObject("Message", "Hello world");
                }
            }

            //We should always call shutdown on comms if we have used it
            NetworkComms.Shutdown();
        }
示例#7
0
        /// <summary>
        /// Create a new connection object
        /// </summary>
        /// <param name="connectionInfo">ConnectionInfo corresponding to the new connection</param>
        /// <param name="defaultSendReceiveOptions">The SendReceiveOptions which should be used as connection defaults</param>
        protected Connection(ConnectionInfo connectionInfo, SendReceiveOptions defaultSendReceiveOptions)
        {
            //If the application layer protocol is disabled the serialiser must be NullSerializer
            //and no data processors are allowed.
            if (connectionInfo.ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Disabled)
            {
                if (defaultSendReceiveOptions.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.", "defaultSendReceiveOptions");
                }

                if (defaultSendReceiveOptions.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.", "defaultSendReceiveOptions");
                }

                if (defaultSendReceiveOptions.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.", "defaultSendReceiveOptions");
                }
            }

            SendTimesMSPerKBCache = new CommsMath();
            packetBuilder         = new PacketBuilder();

            //Initialise the sequence counter using the global value
            //Subsequent values on this connection are guaranteed to be sequential
            packetSequenceCounter = Interlocked.Increment(ref NetworkComms.totalPacketSendCount);

            ConnectionInfo = connectionInfo;

            if (defaultSendReceiveOptions != null)
            {
                ConnectionDefaultSendReceiveOptions = defaultSendReceiveOptions;
            }
            else
            {
                ConnectionDefaultSendReceiveOptions = NetworkComms.DefaultSendReceiveOptions;
            }

            //Add any listener specific packet handlers if required
            if (connectionInfo.ConnectionListener != null)
            {
                connectionInfo.ConnectionListener.AddListenerPacketHandlersToConnection(this);
            }

            if (NetworkComms.commsShutdown)
            {
                throw new ConnectionSetupException("Attempting to create new connection after global NetworkComms.Net shutdown has been initiated.");
            }

            if (ConnectionInfo.ConnectionType == ConnectionType.Undefined || ConnectionInfo.RemoteEndPoint == null)
            {
                throw new ConnectionSetupException("ConnectionType and RemoteEndPoint must be defined within provided ConnectionInfo.");
            }

            //If a connection already exists with this info then we can throw an exception here to prevent duplicates
            if (NetworkComms.ConnectionExists(connectionInfo.RemoteEndPoint, connectionInfo.LocalEndPoint, connectionInfo.ConnectionType, connectionInfo.ApplicationLayerProtocol))
            {
                throw new ConnectionSetupException("A " + connectionInfo.ConnectionType.ToString() + " connection already exists with info " + connectionInfo);
            }

            //We add a reference in the constructor to ensure any duplicate connection problems are picked up here
            NetworkComms.AddConnectionReferenceByRemoteEndPoint(this);
        }
示例#8
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

                #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

                //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
                }
            }
            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
            }

            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();
        }
示例#9
0
 public Server()
 {
     dataSerializer       = DPSManager.GetDataSerializer <ProtobufSerializer>();
     dataProcessors       = new List <DataProcessor>();
     dataProcessorOptions = new Dictionary <string, string>();
 }