Пример #1
0
        protected override void NetMsgRequestMapData(Chunk packet, UnPacker unPacker, int clientId)
        {
            if (packet.Flags.HasFlag(SendFlags.Vital) &&
                Clients[clientId].State != ServerClientState.Connecting)
            {
                return;
            }

            var chunkSize = MapChunkSize;

            for (var i = 0; i < Config["SvMapDownloadSpeed"] && Clients[clientId].MapChunk >= 0; i++)
            {
                var chunk  = Clients[clientId].MapChunk;
                var offset = chunk * chunkSize;

                if (offset + chunkSize >= CurrentMap.Size)
                {
                    chunkSize = CurrentMap.Size - offset;
                    Clients[clientId].MapChunk = -1;
                }
                else
                {
                    Clients[clientId].MapChunk++;
                }

                var msg = new MsgPacker((int)NetworkMessages.ServerMapData, true);
                msg.AddRaw(CurrentMap.RawData, offset, chunkSize);
                SendMsg(msg, MsgFlags.Vital | MsgFlags.Flush, clientId);

                Debug.Log("server", $"sending chunk {chunk} with size {chunkSize}");
            }
        }
Пример #2
0
        protected override bool StartNetworkServer()
        {
            var bindAddr = NetworkCore.GetLocalIP(AddressFamily.InterNetwork);

            if (!string.IsNullOrWhiteSpace(Config["Bindaddr"]))
            {
                bindAddr = IPAddress.Parse(Config["Bindaddr"]);
            }

            var networkConfig = new NetworkServerConfig
            {
                LocalEndPoint   = new IPEndPoint(bindAddr, Config["SvPort"]),
                MaxClientsPerIp = Config["SvMaxClientsPerIP"],
                MaxClients      = Config["SvMaxClients"]
            };

            if (!NetworkServer.Open(networkConfig))
            {
                Debug.Error("server", $"couldn't open socket. port {networkConfig.LocalEndPoint.Port} might already be in use");
                return(false);
            }

            Debug.Log("server", $"network server running at: {networkConfig.LocalEndPoint}");
            return(true);
        }
Пример #3
0
        protected override bool StartNetworkServer()
        {
            var bindAddr = NetworkHelper.GetLocalIP(AddressFamily.InterNetwork);

            if (!string.IsNullOrWhiteSpace(Config["Bindaddr"]))
            {
                bindAddr = IPAddress.Parse(Config["Bindaddr"]);
            }

            var networkConfig = new NetworkServerConfig
            {
                BindEndPoint     = new IPEndPoint(bindAddr, Config["SvPort"]),
                MaxClientsPerIp  = Math.Clamp(Config["SvMaxClientsPerIP"], 1, MaxClients),
                MaxClients       = Math.Clamp(Config["SvMaxClients"], 1, MaxClients),
                ConnectionConfig = new ConnectionConfig
                {
                    Timeout = Config["ConnTimeout"]
                }
            };

            if (!NetworkServer.Open(networkConfig))
            {
                Debug.Error("server", $"couldn't open socket. port {networkConfig.BindEndPoint.Port} might already be in use");
                return(false);
            }

            NetworkServer.ClientConnected    += ClientConnected;
            NetworkServer.ClientDisconnected += ClientDisconnected;
            Debug.Log("server", $"network server running at: {networkConfig.BindEndPoint}");
            return(true);
        }
Пример #4
0
        public override T SnapshotItem <T>(int id)
        {
            Debug.Assert(id >= 0 && id <= 65535, "incorrect id");

            return(id < 0
                ? null
                : SnapshotBuilder.NewItem <T>(id));
        }
Пример #5
0
 public override void AddGametype <T>(string gameType)
 {
     gameType = gameType.ToLower();
     if (GameTypes.ContainsKey(gameType))
     {
         Debug.Warning("server", $"Gametype '{gameType}' already exist");
     }
     GameTypes.Add(gameType, typeof(T));
 }
Пример #6
0
        private void SendMapData(int last, int chunk, int chunkSize,
                                 int offset, int clientId)
        {
            var msg = new MsgPacker((int)NetworkMessages.SV_MAP_DATA);

            msg.AddInt(last);
            msg.AddInt((int)CurrentMap.CRC);
            msg.AddInt(chunk);
            msg.AddInt(chunkSize);
            msg.AddRaw(CurrentMap.RawData, offset, chunkSize);
            SendMsgEx(msg, MsgFlags.FLUSH, clientId, true);

            Debug.Log("server", $"sending chunk {chunk} with size {chunkSize}");
        }
Пример #7
0
        protected override void RandomRconPassword()
        {
            const int    PasswordLength = 6;
            const string PasswordChars  = "ABCDEFGHKLMNPRSTUVWXYZabcdefghjkmnopqt23456789";

            Debug.Assert(PasswordLength % 2 == 0, "Need an even password length");

            var password = new StringBuilder(PasswordLength);
            var random   = new ushort[PasswordLength / 2];

            Secure.RandomFill(random);

            for (var i = 0; i < PasswordLength / 2; i++)
            {
                var randomNumber = random[i] % 2048;
                password.Append(PasswordChars[randomNumber / PasswordChars.Length]);
                password.Append(PasswordChars[randomNumber % PasswordChars.Length]);
            }

            ((ConfigString)Config["SvRconPassword"]).Value = password.ToString();
        }
Пример #8
0
        public override GameController GameController(string gameType)
        {
            Type type;

            try
            {
                type = GameTypes
                       .First(kvp => kvp.Key.Equals(gameType, StringComparison.InvariantCultureIgnoreCase))
                       .Value;
            }
            catch (Exception)
            {
                Debug.Exception("server", $"Gametype '{gameType}' not found");
                throw;
            }

            var gameController = (GameController)Activator.CreateInstance(type);

            Debug.Log("server", $"Create gamecontroller '{gameController.GameType}'");
            return(gameController);
        }
Пример #9
0
 public override bool SnapshotItem <T>(T item, int id)
 {
     Debug.Assert(id >= 0 && id <= 65535, "incorrect id");
     return(id >= 0 && SnapshotBuilder.AddItem(item, id));
 }
Пример #10
0
        public override void Run()
        {
            if (IsRunning)
            {
                return;
            }

            Debug.Log("server", "starting...");

            if (!LoadMap(Config["SvMap"]))
            {
                Debug.Error("server", $"failed to load map. mapname='{Config["SvMap"]}'");
                return;
            }

            if (!StartNetworkServer())
            {
                return;
            }

            Console.Print(OutputLevel.Standard, "server", $"server name is '{Config["SvName"]}'");
            GameContext.Init();
            GameContext.RegisterCommandsUpdates();
            RegisterConsoleUpdates();

            StartTime = Time.Get();
            IsRunning = true;

            if (string.IsNullOrEmpty(Config["SvRconPassword"]))
            {
                RandomRconPassword();
                Debug.Assert(false, "+-------------------------+");
                Debug.Assert(false, $"| rcon password: '******' |");
                Debug.Assert(false, "+-------------------------+");
            }

            while (IsRunning)
            {
                var now   = Time.Get();
                var ticks = 0;

                while (now > TickStartTime(Tick + 1))
                {
                    Tick++;
                    ticks++;

                    for (var clientId = 0; clientId < Clients.Length; clientId++)
                    {
                        if (Clients[clientId].State != ServerClientState.InGame)
                        {
                            continue;
                        }

                        for (var inputIndex = 0; inputIndex < Clients[clientId].Inputs.Length; inputIndex++)
                        {
                            if (Clients[clientId].Inputs[inputIndex].Tick != Tick)
                            {
                                continue;
                            }

                            GameContext.OnClientPredictedInput(clientId, Clients[clientId].Inputs[inputIndex].Data);
                            break;
                        }
                    }

                    GameContext.OnTick();
                }

                if (ticks != 0)
                {
                    if (Tick % 2 == 0 || Config["SvHighBandwidth"])
                    {
                        DoSnapshot();
                    }
                    SendClientRconCommands();
                }

                //Register.RegisterUpdate(NetworkServer.NetType());
                PumpNetwork();

                Thread.Sleep(5);
            }

            for (var i = 0; i < Clients.Length; i++)
            {
                if (Clients[i].State != ServerClientState.Empty)
                {
                    Kick(i, "Server shutdown");
                }
            }

            GameContext.OnShutdown();
        }
Пример #11
0
        public override void Run()
        {
            if (IsRunning)
            {
                return;
            }

            Debug.Log("server", "starting...");

            if (!LoadMap(Config["SvMap"]))
            {
                Debug.Error("server", $"failed to load map. mapname='{Config["SvMap"]}'");
                return;
            }

            if (!StartNetworkServer())
            {
                return;
            }

            Clients = new BaseServerClient[NetworkServer.ServerConfig.MaxClients];
            IdMap   = new int[Clients.Length * VANILLA_MAX_CLIENTS];

            for (var i = 0; i < Clients.Length; i++)
            {
                Clients[i] = Kernel.Get <BaseServerClient>();
            }

            NetworkServer.SetCallbacks(NewClientCallback, DelClientCallback);
            Console.Print(OutputLevel.STANDARD, "server", $"server name is '{Config["SvName"]}'");
            GameContext.OnInit();

            StartTime = Time.Get();
            IsRunning = true;

            _lastSent    = new int[NetworkServer.ServerConfig.MaxClients];
            _lastAsk     = new int[NetworkServer.ServerConfig.MaxClients];
            _lastAskTick = new int[NetworkServer.ServerConfig.MaxClients];

            while (IsRunning)
            {
                var now   = Time.Get();
                var ticks = 0;

                while (now > TickStartTime(Tick + 1))
                {
                    Tick++;
                    ticks++;

                    for (var clientId = 0; clientId < Clients.Length; clientId++)
                    {
                        if (Clients[clientId].State != ServerClientState.IN_GAME)
                        {
                            continue;
                        }

                        for (var inputIndex = 0; inputIndex < Clients[clientId].Inputs.Length; inputIndex++)
                        {
                            if (Clients[clientId].Inputs[inputIndex].Tick == Tick)
                            {
                                GameContext.OnClientPredictedInput(clientId,
                                                                   Clients[clientId].Inputs[inputIndex].PlayerInput);
                                break;
                            }
                        }
                    }

                    GameContext.OnTick();
                }

                if (ticks != 0)
                {
                    if (Tick % 2 == 0 || Config["SvHighBandwidth"])
                    {
                        DoSnapshot();
                    }
                    // UpdateClientRconCommands()
                }

                Register.RegisterUpdate(NetworkServer.NetType());
                PumpNetwork();

                Thread.Sleep(5);
            }

            for (var i = 0; i < Clients.Length; i++)
            {
                if (Clients[i].State != ServerClientState.EMPTY)
                {
                    NetworkServer.Drop(i, "Server shutdown");
                }
            }

            GameContext.OnShutdown();
        }