Task <string> ICommunicationListener.OpenAsync(CancellationToken cancellationToken)
            {
                var endpoint = FabricRuntime.GetActivationContext().GetEndpoint(this._endpointName);

                var address    = FabricRuntime.GetNodeContext().IPAddressOrFQDN;
                var serverUrls =
                    ImmutableArray.Create(
                        $"{endpoint.Protocol}://{address}:{endpoint.Port}");

                if (!LocalAddresses.Contains(address))
                {
                    serverUrls = serverUrls.Add($"{endpoint.Protocol}://localhost:{endpoint.Port}");
                }

                this.webHost =
                    new WebHostBuilder().UseKestrel()
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .UseStartup <Startup>()
                    .UseUrls(serverUrls.ToArray())
                    .UseServiceFabricContext(this.Context)
                    .Build();
                this.webHost.Start();

                return(Task.FromResult(serverUrls[0]));
            }
        /// <summary>
        /// Deinitialization method cleaning all the created objects
        /// </summary>
        public async Task Deinitialize()
        {
            //Client should wait for master to break the connection
            if (IsClient)
            {
                while (Client.Connection.ConnectedPeersCount > 0)
                {
                    await Task.Delay(20);
                }
            }
            StopConnection();

            var type = Type;
            var clearObjectsAction = new Action(() =>
            {
                ClearNetworkObjects(type);
            });

            ThreadingUtilities.DispatchToMainThread(clearObjectsAction);

            LocalAddresses.Clear();
            MasterAddresses.Clear();
            Type = ClusterNodeType.NotClusterNode;
            CurrentSimulation = null;
            Log.Info("Deinitialized the Simulation Network data.");
        }
Beispiel #3
0
        protected virtual void ClientPacketReceived(object sender, PacketEventArgs e)
        {
            if (!(sender is ISocket socket))
            {
                return;
            }

            Stats.PacketsReceived++;
            Stats.AddInput(e.Transferred);

            //only allow connections from WebSockets?
            if (!Config.UseTcpSockets && !socket.IsWebSocket)
            {
                socket.Disconnect();
                return;
            }

            if ((AresId)e.Packet.Id == AresId.MSG_CHAT_CLIENT_LOGIN)
            {
                IClient user = Users.Find(s => s.Socket == socket);

                if (user == null)
                {
                    if (HandlePending(socket))
                    {
                        int id     = idpool.Pop();
                        var client = new AresClient(this, socket, (ushort)id);

                        if (IPAddress.IsLoopback(client.ExternalIp) ||
                            client.ExternalIp.Equals(ExternalIp) ||
                            LocalAddresses.Contains(client.ExternalIp) ||
                            (Config.LocalAreaIsHost && client.ExternalIp.IsLocalAreaNetwork()))
                        {
                            client.LocalHost = true;
                        }

                        lock (Users) {
                            Users.Add(client);
                            Users.Sort(sorter);
                            Stats.PeakUsers = Math.Max(Users.Count, Stats.PeakUsers);
                        }

                        client.HandleJoin(e);
                    }
                    else
                    {
                        socket.Disconnect();
                    }
                }
                else
                {
                    //sending too many login packets
                    SendAnnounce(user, Errors.LoginFlood);
                    Logging.Info("AresServer", "User '{0}' has been disconnected for login flooding.", user.Name);

                    user.Disconnect();
                }
            }
        }
Beispiel #4
0
    public void ScanHost()
    {
        IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());

        foreach (IPAddress ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                string address    = ip.ToString();
                string subAddress = address.Remove(address.LastIndexOf('.'));

                //if (!LocalAddresses.Contains(address))
                //{
                LocalAddresses.Add(address);
                //}

                if (!LocalSubAddresses.Contains(subAddress))
                {
                    LocalSubAddresses.Add(subAddress);
                }
            }
        }
    }
Beispiel #5
0
    private void ReceiveClient(IAsyncResult ar)
    {
        if (socketClient != null)
        {
            try
            {
                int    size    = socketClient.EndReceiveFrom(ar, ref remoteEndPoint);
                string address = remoteEndPoint.ToString().Split(':')[0];

                // This is not ourself and we do not already have this address
                if (!LocalAddresses.Contains(address) && !Addresses.Contains(address))
                {
                    Addresses.Add(address);
                }

                socketClient.BeginReceiveFrom(new byte[1024], 0, 1024, SocketFlags.None,
                                              ref remoteEndPoint, new AsyncCallback(ReceiveClient), null);
            }
            catch (Exception ex)
            {
                Debug.Log(ex.ToString());
            }
        }
    }
Beispiel #6
0
        /// <summary>
        /// Initialization method for setting up the simulation network
        /// </summary>
        /// <param name="simulationId">This machine simulation id</param>
        /// <param name="clusterData">Cluster data for this simulation</param>
        /// <param name="settings">Settings used in this simulation</param>
        public void Initialize(string simulationId, ClusterData clusterData, NetworkSettings settings)
        {
            ClusterData = clusterData;
            Settings    = settings;

            //Check what cluster node type is this machine in the simulation
            if (ClusterData.Instances.Length <= 1)
            {
                Type = ClusterNodeType.NotClusterNode;
            }
            else
            {
                //Set this machine type
                var instancesData = ClusterData.Instances.Where(instance => instance.SimId == simulationId).ToArray();
                var resultsCount  = instancesData.Length;
                if (resultsCount == 0)
                {
                    throw new ArgumentException(
                              $"Invalid cluster settings. Could not find instance data for the simulation id '{simulationId}'.");
                }
                if (resultsCount > 1)
                {
                    throw new ArgumentException(
                              $"Invalid cluster settings. Found multiple instance data for the simulation id '{simulationId}'.");
                }
                var thisInstanceData = instancesData[0];
                Type            = thisInstanceData.IsMaster ? ClusterNodeType.Master : ClusterNodeType.Client;
                LocalIdentifier = thisInstanceData.SimId;
                foreach (var ip in thisInstanceData.Ip)
                {
                    LocalAddresses.Add(new IPEndPoint(IPAddress.Parse(ip), Settings.ConnectionPort));
                }

                //Setup master addresses
                var masterInstanceData = ClusterData.Instances.Where(instance => instance.IsMaster).ToArray();
                resultsCount = masterInstanceData.Length;
                if (resultsCount == 0)
                {
                    throw new ArgumentException($"Invalid cluster settings. Could not find master instance data.");
                }
                if (resultsCount > 1)
                {
                    throw new ArgumentException($"Invalid cluster settings. Found multiple master instance data.");
                }
                MasterIdentifier = masterInstanceData[0].SimId;
                foreach (var ip in masterInstanceData[0].Ip)
                {
                    MasterAddresses.Add(new IPEndPoint(IPAddress.Parse(ip), Settings.ConnectionPort));
                }
            }

            //Initialize network objects
            var mainThreadDispatcher = Object.FindObjectOfType <MainThreadDispatcher>();

            if (mainThreadDispatcher == null)
            {
                var dispatcher = new GameObject("MainThreadDispatcher");
                Object.DontDestroyOnLoad(dispatcher);
                dispatcher.AddComponent <MainThreadDispatcher>();
            }
            if (Type == ClusterNodeType.Master)
            {
                var masterGameObject = new GameObject("MasterManager");
                Object.DontDestroyOnLoad(masterGameObject);
                Master = masterGameObject.AddComponent <MasterManager>();
                Master.SetSettings(Settings);
                var clientsIdentifiers = ClusterData.Instances.Where(instanceData => !instanceData.IsMaster)
                                         .Select(instanceData => instanceData.SimId).ToList();
                Master.StartConnection(clientsIdentifiers);
            }
            else if (Type == ClusterNodeType.Client)
            {
                var clientGameObject = new GameObject("ClientManager");
                Object.DontDestroyOnLoad(clientGameObject);
                Client = clientGameObject.AddComponent <ClientManager>();
                clientGameObject.AddComponent <MainThreadDispatcher>();
                Client.SetSettings(Settings);
                Client.StartConnection();
                Client.TryConnectToMaster();
            }
            Log.Info("Initialized the Simulation Network data.");
        }
Beispiel #7
0
        protected virtual void ClientPacketReceived(object sender, PacketEventArgs e)
        {
            if (!(sender is ISocket socket))
            {
                return;
            }

            Stats.PacketsReceived++;
            Stats.AddInput(e.Transferred);

            if (e.Packet.Id == (byte)AresId.MSG_CHAT_CLIENT_LOGIN)
            {
                IClient user = Users.Find(s => s.Socket == socket);

                if (user == null)
                {
                    if (HandlePending(socket))
                    {
                        if (idpool.Count == 0)
                        {
                            socket.SendAsync(new Announce(Errors.RoomFull));
                            socket.Disconnect();
                            Logging.Info(
                                "AresServer",
                                "Chatroom has reached capacity ({0}). If this happens frequently consider raising Max Clients",
                                Config.MaxClients
                                );
                        }
                        else
                        {
                            int id     = idpool.Pop();
                            var client = new AresClient(this, socket, (ushort)id);

                            if (IPAddress.IsLoopback(client.ExternalIp) ||
                                client.ExternalIp.Equals(ExternalIp) ||
                                LocalAddresses.Contains(client.ExternalIp) ||
                                (Config.LocalAreaIsHost && client.ExternalIp.IsLocalAreaNetwork()))
                            {
                                client.LocalHost = true;
                            }

                            lock (Users) {
                                Users.Add(client);
                                Users.Sort(sorter);
                                Stats.PeakUsers = Math.Max(Users.Count, Stats.PeakUsers);
                            }

                            client.HandleJoin(e);
                        }
                    }
                }
                else
                {
                    //sending too many login packets
                    SendAnnounce(user, Errors.LoginFlood);
                    Logging.Info("AresServer", "User '{0}' has been disconnected for login flooding.", user.Name);

                    user.Disconnect();
                }
            }
        }