Start() private method

private Start ( ) : void
return void
Example #1
0
    /// <summary>
    /// Start a new server.
    /// </summary>

    bool StartLocal(int tcpPort, int udpPort, string fileName, int lobbyPort, Type type)
    {
        // Ensure that everything has been stopped first
        if (mGame.isActive)
        {
            Disconnect();
        }

        // If there is a lobby port, we should set up the lobby server and/or link first.
        // Doing so will let us inform the lobby that we are starting a new server.

        if (lobbyPort > 0)
        {
            if (type == Type.Tcp)
            {
                mLobby = new TcpLobbyServer();
            }
            else
            {
                mLobby = new UdpLobbyServer();
            }

            // Start a local lobby server
            if (mLobby.Start(lobbyPort))
            {
                if (type == Type.Tcp)
                {
                    mUp.OpenTCP(lobbyPort);
                }
                else
                {
                    mUp.OpenUDP(lobbyPort);
                }
            }
            else
            {
                mLobby = null;
                return(false);
            }

            // Create the local lobby link
            mGame.lobbyLink = new LobbyServerLink(mLobby);
        }

        // Start the game server
        if (mGame.Start(tcpPort, udpPort))
        {
            mUp.OpenTCP(tcpPort);
            mUp.OpenUDP(udpPort);
            if (!string.IsNullOrEmpty(fileName))
            {
                mGame.LoadFrom(fileName);
            }
            return(true);
        }

        // Something went wrong -- stop everything
        Disconnect();
        return(false);
    }
Example #2
0
        static void Main(string[] args)
        {
            var settings = ReadSettings(Program.Location + "Settings.xml");

            Console.WriteLine("Name: " + settings.Name);
            Console.WriteLine("Port: " + settings.Port);
            Console.WriteLine("Player Limit: " + settings.MaxPlayers);
            Console.WriteLine("Starting...");

            ServerInstance = new GameServer(settings.Port, settings.Name, settings.Gamemode);
            ServerInstance.PasswordProtected = settings.PasswordProtected;
            ServerInstance.Password = settings.Password;
            ServerInstance.AnnounceSelf = settings.Announce;
            ServerInstance.MasterServer = settings.MasterServer;
            ServerInstance.MaxPlayers = settings.MaxPlayers;

            ServerInstance.Start(settings.Filterscripts);

            Console.WriteLine("Started! Waiting for connections.");

            while (true)
            {
                ServerInstance.Tick();
            }
        }
Example #3
0
        public static void RunServerWith(int numberOfClients)
        {
            var port = 50051;

            GameServer server = new GameServer(port);

            server.Start();

            var matchMaker = server.GetMatchMakerService();

            matchMaker.Start(7);

            Task <GameClient>[] tasks = new Task <GameClient> [numberOfClients];

            for (int i = 0; i < numberOfClients; i++)
            {
                int index = i;

                tasks[index] = CreateGameClientTask(port, $"TestClient{index}", "", new RandomAI());
            }


            Console.WriteLine("Press any key to stop.");
            Console.ReadKey();
            server.Stop();
        }
        private static void StartServers()
        {
#if DEBUG
            Config.DebugMode = true;
#endif
redo:
            {
                if (Errors > Config.ERRORCAP)
                {
                    Process.GetCurrentProcess().Kill();
                }

                try
                {
                    Game = new GameServer(Config.ConnectionCapacity);
                    Game.Start(DefaultPort);

                    Lobby = new LoginServer(Config.ConnectionCapacity);
                    Lobby.Start(2610);
                }
                catch (SocketException e)
                {
                    Report(e);
                    {
                        ++DefaultPort;
                        Errors++;
                    }
                    goto redo;
                }
            }
        }
Example #5
0
        public static void RunServerWith(int numberOfClients)
        {
            var port = 50051;

            GameServer server = new GameServer(port);

            server.Start();

            var matchMaker = server.GetMatchMakerService();

            matchMaker.Start(1);

            GameClient[] tasks = new GameClient[numberOfClients];

            for (int i = 0; i < numberOfClients; i++)
            {
                int index = i;

                tasks[index] = CreateGameClientTask("127.0.0.1", port, $"TestClient{index}", "", new RandomAI());
            }

            while (tasks.Any(p => p.GameClientState != GameClientState.None))
            {
                Thread.Sleep(100);
            }

            server.Stop();
        }
Example #6
0
        public static void Initialize()
        {
            GetHostByNameHook.Install();
            ConnectHook.Install();
            SendHook.InstallSend();
            SendHook.InstallRecv();
            PortPatch.Apply();
            DisableEncryptionPatch.Apply();
            GameProtocolHook.Install2((msgid, msg) =>
            {
                Debugging.Debug.Log("msg: " + msgid.ToString());
            });

            GameProtocolHook.Install((gameProtocol, type) =>
            {
                Debugging.Debug.Log(gameProtocol.ToString() + ", " + type.ToString());
                if (type == 0)
                {
                    GameServer.Protocol = new Protocol.Protocol(gameProtocol);
                }
                else if (type == 3)
                {
                    AuthServer.Protocol = new Protocol.Protocol(gameProtocol);
                }
                else
                {
                    Debugging.Debug.Log("Unknown protocol type: " + gameProtocol.ToString() + ", " + type.ToString());
                }
            });

            _fileServer.Start();
            AuthServer.Start();
            GameServer.Start();
        }
Example #7
0
        private static void StartServers()
        {
#if DEBUG
            ServerContext.Config.DebugMode = true;
#endif

redo:
            {
                if (Errors > Config.ERRORCAP)
                {
                    Process.GetCurrentProcess().Kill();
                }

                try
                {
                    Game = new GameServer(Config.ConnectionCapacity);
                    Game.Start(DefaultPort);
                }
                catch (Exception)
                {
                    { ++DefaultPort; Errors++; }
                    goto redo;
                }
            }


            Running = true;
        }
Example #8
0
        static void Main(string[] args)
        {
            // 创建数据库管理
            DataMgr dataMgr = new DataMgr();
            // 创建玩家管理实例
            PlayerMgr playerMgr = new PlayerMgr();
            //创建房间管理器实例
            RoomMgr roomMgr = new RoomMgr();

            // 创建服务器实例
            GameServer serv = new GameServer();

            // 打开服务器
            serv.Start(7000, 7001);

            while (true)
            {
                string str = Console.ReadLine();
                switch (str)
                {
                case "quit":
                    serv.Close();
                    return;

                case "print":

                    break;
                }
            }
        }
Example #9
0
        static void Main(string[] args)
        {
            RouteManager.RegistAssembly(Assembly.GetEntryAssembly());
            BattleMatchManager.Instance.Start();
            GameServer.Start(Config.GamePort);
            FightServer.Instance.Start(Config.MahjongPort);
            PokerServer.Instance.Start(Config.PokerPort);

            //List<WinCardModel> ret = WinALG.Win(WinTestCards.test13(), false);
            //if (ret.Count == 0)
            //    Console.WriteLine("没胡");
            //else
            //{
            //    foreach (var w in ret)
            //    {
            //        Console.WriteLine("胡了{0}番,{1}", w.GetTurnNum(), w.ToString());
            //    }
            //}

            //List<Card> ret = ChessHelper.CanListenCardList(WinTestCards.daduifu333());
            //if (ret.Count == 0)
            //    Console.WriteLine("无听牌");
            //else
            //{
            //    foreach (var w in ret)
            //    {
            //        Console.WriteLine("听:" + w.ToString());
            //    }
            //}
            Console.Read();
        }
        private static void StartServers()
        {
            Running = false;

redo:
            if (ERRORS > Config.ERRORCAP)
            {
                Process.GetCurrentProcess().Kill();
            }

            try
            {
                Lobby = new LoginServer(Config.ConnectionCapacity);
                Lobby.Start(Config.LOGIN_PORT);
                Game = new GameServer(Config.ConnectionCapacity);
                Game.Start(DEFAULT_PORT);

                Running = true;
            }
            catch (Exception)
            {
                ++DEFAULT_PORT;
                ERRORS++;
                goto redo;
            }
        }
Example #11
0
        static void Main(string[] args)
        {
            var settings = ReadSettings(Program.Location + "Settings.xml");

            Console.WriteLine("Name: " + settings.Name);
            Console.WriteLine("Port: " + settings.Port);
            Console.WriteLine("Player Limit: " + settings.MaxPlayers);
            Console.WriteLine("Starting...");

            ServerInstance = new GameServer(settings.Port, settings.Name, settings.Gamemode);
            ServerInstance.PasswordProtected = settings.PasswordProtected;
            ServerInstance.Password = settings.Password;
            ServerInstance.AnnounceSelf = settings.Announce;
            ServerInstance.MasterServer = settings.MasterServer;
            ServerInstance.MaxPlayers = settings.MaxPlayers;
            ServerInstance.AllowDisplayNames = settings.AllowDisplayNames;

            ServerInstance.Start(settings.Filterscripts);

            Console.WriteLine("Started! Waiting for connections.");

            while (true)
            {
                ServerInstance.Tick();
                System.Threading.Thread.Sleep(10); // Reducing CPU Usage (Win7 from average 15 % to 0-1 %, Linux from 100 % to 0-2 %)
            }
        }
Example #12
0
        static void Main(string[] args)
        {
            GameServer server = new GameServer();

            server.Start();

            Console.ReadKey();
        }
Example #13
0
        public static void Main(string[] args)
        {
            // No DI here because MapleServer is static
            Logger logger = LogManager.GetCurrentClassLogger();

            logger.Info($"MapleServer started with {args.Length} args: {string.Join(", ", args)}");

            IContainer loginContainer = LoginContainerConfig.Configure();

            using ILifetimeScope loginScope = loginContainer.BeginLifetimeScope();
            LoginServer loginServer = loginScope.Resolve <LoginServer>();

            loginServer.Start();

            IContainer gameContainer = GameContainerConfig.Configure();

            using ILifetimeScope gameScope = gameContainer.BeginLifetimeScope();
            gameServer = gameScope.Resolve <GameServer>();
            gameServer.Start();

            // Input commands to the server
            while (true)
            {
                string[] input = (Console.ReadLine() ?? string.Empty).Split(" ", 2);
                switch (input[0])
                {
                case "exit":
                case "quit":
                    gameServer.Stop();
                    loginServer.Stop();
                    return;

                case "send":
                    string       packet  = input[1].Replace(" ", "");
                    PacketWriter pWriter = new PacketWriter();
                    pWriter.Write(packet.ToByteArray());
                    logger.Info(pWriter);

                    foreach (Session session in GetSessions(loginServer, gameServer))
                    {
                        logger.Info($"Sending packet to {session}: {pWriter}");
                        session.Send(pWriter);
                    }

                    break;

                case "resolve":
                    PacketStructureResolver resolver = PacketStructureResolver.Parse(input[1]);
                    GameSession             first    = gameServer.GetSessions().Single();
                    resolver.Start(first);
                    break;

                default:
                    logger.Info($"Unknown command:{input[0]} args:{(input.Length > 1 ? input[1] : "N/A")}");
                    break;
                }
            }
        }
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
            Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
            System.Net.ServicePointManager.DefaultConnectionLimit = 512;
            ThreadPool.SetMaxThreads(128, 256);
            //
            Config = new ServerConfig();
            bool loaded = args.Length > 0 ? Config.Load(args[0]): Config.Load();
            int  tmp    = 0;

            if (args.Length > 1)
            {
                int.TryParse(args[1], out tmp);
                if (tmp > 0)
                {
                    Config.SetServerPort(tmp);
                }
            }
            if (args.Length > 2)
            {
                int.TryParse(args[2], out tmp);
                if (tmp > 0)
                {
                    Config.SetApiPort(tmp);
                }
            }
            if (args.Length > 3)
            {
                Config.SetNeedAuth(args[3].Trim().ToLower() == "true");
            }
            Logger.SetErrorFile(Tool.Combine(Config.Path, "error_" + DateTime.UtcNow.ToString("yyyy-MM-dd") + "_" + Config.ServerPort + ".log"));
            Logger.SetLogLevel(Config.LogLevel);
#if DEBUG
            Logger.SetLogLevel(LogLevel.Debug);
#endif
            Console.Title = "GameServer:" + Config.ServerPort;
            GameServer Server = new GameServer(Config);
            Server.WriteHead();
            if (loaded)
            {
                Logger.Debug("Config loaded.");
            }
            else
            {
                Logger.Warn("Unable to load config.txt, using default settings.");
            }
            if (!Server.Start())
            {
                Console.WriteLine(">>server start fail.");
                Console.ReadKey();
            }
            else
            {
                Command(Server);
            }
        }
Example #15
0
        static void Main(string[] args)
        {
            var settings = ReadSettings(Program.Location + "settings.xml");

            Console.WriteLine("=======================================================================");
            Console.WriteLine("= MultiV Server v1.0");
            Console.WriteLine("=======================================================================");
            Console.WriteLine("= Server Name: " + settings.Name);
            Console.WriteLine("= Server Port: " + settings.Port);
            Console.WriteLine("=");
            Console.WriteLine("= Player Limit: " + settings.MaxPlayers);
            Console.WriteLine("=======================================================================");

            if (settings.Port != 4499)
            {
                Output("WARN: Port is not the default one, players on your local network won't be able to automatically detect you!");
            }

            Output("Starting...");

            var config = new ServerConfig();

            config.PasswordProtected = !String.IsNullOrWhiteSpace(settings.Password);
            config.Password          = settings.Password;
            config.AnnounceSelf      = settings.Announce;
            config.MasterServer      = settings.MasterServer;
            config.MaxPlayers        = settings.MaxPlayers;
            config.ACLEnabled        = settings.UseACL;
            config.Name = settings.Name;
            config.Port = settings.Port;


            ServerInstance = new GameServer(config);
            ServerInstance.AllowDisplayNames = true;

            ServerInstance.Start(settings.Resources.Select(r => r.Path).ToArray());

            Output("Started! Waiting for connections.");

            if (Type.GetType("Mono.Runtime") == null)
            {
                SetConsoleCtrlHandler(new HandlerRoutine(ConsoleCtrlCheck), true);
            }
            else
            {
                Console.CancelKeyPress += (sender, eventArgs) =>
                {
                    ConsoleCtrlCheck(CtrlTypes.CTRL_C_EVENT);
                };
            }

            while (!CloseProgram)
            {
                ServerInstance.Tick();
                Thread.Sleep(1000 / 60);
            }
        }
        async Task <byte[]> RunAsyncRoomServer()
        {
            await Task.Run(() => {
                server = new GameServer();
                server.Start();
            });

            return(null);
        }
Example #17
0
        private static void Main()
        {
            LogHelp.Init(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "LogConfig.log4net"));
            LogHelp.TestLog();
            log = LogHelp.GetLogger(typeof(Program));

            Console.SetIn(new StreamReader(Console.OpenStandardInput(8192)));

            log.Info("Hello Server!");

            Server = new GameServer(128, 8192);
            Server.Init(2048);
            // 反序列化消息
            Server.MessageHandler.SetDeserializeFunc((bytes, guid) =>
            {
                var protoId = BitConverter.ToInt32(bytes);
                return(new ExtSocket {
                    Protocol = ProtocolParser.Instance.GetParser(protoId).ParseFrom(bytes) as ProtocolBufBase, Guid = guid, ESocketType = ESocketType.ESocketReceive
                });
            });
            // 序列化消息
            Server.MessageHandler.SetSerializeFunc((protocol) =>
            {
                return((protocol as ProtocolBufBase).Serialize());
            });
            Server.Start("127.0.0.1", 11000);

            // 主循环
            stopwatch.Start();
            var t1 = stopwatch.ElapsedMilliseconds;
            var t2 = stopwatch.ElapsedMilliseconds;

            TimerManager.Init();
            SDungeon.Instance.Init();
            while (true)
            {
                t1 = stopwatch.ElapsedMilliseconds;

                // 消息处理
                Server.ProcessMessage();
                // 定时器处理
                TimerManager.Update(stopwatch.ElapsedMilliseconds);

                SDungeon.Instance.Update();
                SNotify.Instance.Update();
                SMove.Instance.Update();

                t2 = stopwatch.ElapsedMilliseconds;
                var t = (int)(t2 - t1);
                System.Threading.Thread.Sleep(t < 30 ? 30 - t : 1);
                if (t > 200)
                {
                    log.Warn($"Performance warning! One tick cost {t} ms!");
                }
            }
        }
Example #18
0
        private static void Main()
        {
            SetConsoleConfigurations();
            SetNumberDecimalSeparator();
            GameServer.Kernel = new StandardKernel(new DepInjectionModule());
            GameServer server = GameServer.Kernel.Get <GameServer>();

            server.Start();
            Process.GetCurrentProcess().WaitForExit();
        }
        protected override void Initialize()
        {
            if (AppSettings.Default.EnableServer)
            {
                GameServer server = new GameServer(new MapGenerator().Generate(30, 16), AppSettings.Default.ListenPort);
                server.Start();
            }
            ApplyGraphicsSettings();

            base.Initialize();
        }
        protected override void Initialize()
        {
            if (AppSettings.Default.EnableServer)
            {
                GameServer server = new GameServer(new MapGenerator().Generate(30, 16), AppSettings.Default.ListenPort);
                server.Start();
            }
            ApplyGraphicsSettings();

            base.Initialize();
        }
Example #21
0
    public void StartServer(GameManager gameManager)
    {
        server = new GameServer(gameManager);

        server.Register <Feed>("feed");
        server.Register <Play>("play");
        server.Register <Groom>("groom");
        server.Register <Pet>("pet");

        server.Start();
    }
Example #22
0
        public static void RunServer()
        {
            var port = 50051;

            GameServer server = new GameServer(port);

            server.Start();

            var matchMaker = server.GetMatchMakerService();

            matchMaker.Start(1);
        }
Example #23
0
        public static void Main(string[] args)
        {
            var opts = options(args);

            opts.TryGetValue("p", out var portStr);
            int.TryParse(portStr ?? "14834", out var serverPort);
            var server = new GameServer(new NetworkConnectionProvider(RemoteGameProtocol.instance,
                                                                      new Target(Target.AnyIP, serverPort), GameServer.MAX_CONNECTIONS));

            server.initializeSimulation();
            server.Start();
        }
Example #24
0
        //starts login and game server
        static ushort StartServers(Client client)
        {
            ushort loginport = Server.Port.GetFreePort();
            ushort gameport  = Server.Port.GetFreePort((ushort)(loginport + 1));

            game = new Server.GameServer(client);
            game.ClientConnected += new EventHandler(game_ClientConnected);
            game.Start(gameport);
            login = new Server.LoginServer(client, loginport);
            login.Start(gameport);
            return(gameport);
        }
        public void PingRequest()
        {
            _server.Start();

            var channel = new Channel(_target, ChannelCredentials.Insecure);

            Assert.Equal(ChannelState.Idle, channel.State);

            var client = new GameServerService.GameServerServiceClient(channel);

            Assert.Equal(ChannelState.Idle, channel.State);

            var reply = client.Ping(new PingRequest {
                Message = string.Empty
            });

            Assert.True(reply.RequestState);
            Assert.Equal("Ping", reply.RequestMessage);

            _server.Stop();
        }
Example #26
0
 void Start()
 {
     server.Start();
     teams = new[]
     {
         NoTeamWins, BlueTeamWins, RedTeamWins
     };
     ResetText.SetActive(false);
     RedTeamWins.SetActive(false);
     BlueTeamWins.SetActive(false);
     NoTeamWins.SetActive(false);
 }
Example #27
0
        public static void Start()
        {
            lock (_lock) {
                if (!_initialized)
                {
                    return;
                }

                _gameServer.Start();
                _policyServer.Start();
                _chatServer.Start();
            }
        }
Example #28
0
        public static void LoadServers()
        {
            LobbyServer = new LobbyServer();
            GameServers = new List <GameServer>();

            string[] directories = Directory.GetDirectories("GameServers");
            foreach (string directory in directories)
            {
                if (File.Exists(directory + "\\config.xml"))
                {
                    GameServer gs = new GameServer(directory);
                    gs.Index = GameServers.Count;
                    GameServers.Add(gs);
                    gs.LoginServer.Start();
                    gs.Start();
                }
            }

            string decPath = (StartupPath + "\\mServer_dec");
            string encPath = (StartupPath + "\\mServer_enc");

            using (Stream stream = File.Create(decPath))
            {
                using (BinaryWriter writer = new BinaryWriter(stream, Encoding.GetEncoding(949)))
                {
                    byte i = 0;
                    writer.Write((byte)GameServers.Count);
                    foreach (GameServer gs in GameServers)
                    {
                        byte[] addressBytes = gs.LoginServer.EndPoint.Address.GetAddressBytes();
                        Array.Reverse(addressBytes);
                        writer.Write(i++);
                        writer.Write(addressBytes);
                        writer.Write((byte)(gs.LoginServer.EndPoint.Port / 256));
                        writer.Write((byte)(gs.LoginServer.EndPoint.Port % 256));
                        writer.Write(Encoding.GetEncoding(949).GetBytes(string.Format("{0};{1}\0", gs.Name, gs.Description)));
                        writer.Write((byte)0x00);
                    }
                }
            }

            Checksum = ~CRC32.Calculate(File.ReadAllBytes(decPath));
            ZLIB.Compress(decPath, encPath);
            RawData = File.ReadAllBytes(encPath);

            File.Delete(decPath);
            File.Delete(encPath);

            Program.WriteLine("{0} game servers loaded!", GameServers.Count);
            LobbyServer.Start();
        }
        private void cmdStartServer_Click(object sender, RoutedEventArgs e)
        {
            if (started)
            {
                return;
            }
            started = true;

            lstServerOutput.Items.Add("服务器已启动");
            GameServer.Report += s =>
            {
                this.Dispatcher.Invoke(() => lstServerOutput.Items.Add(s));
            };
            GameServer.Start();
        }
        public void Start()
        {
            // reset state
            GameServer.Stop();
            unityServer = Substitute.For <IUnityServer>();

            unityServer.StartServer().Returns(false);
            Assert.Throws <Exception>(() => GameServer.Start(unityServer));
            unityServer.Received(10).StartServer();

            unityServer.ClearReceivedCalls();
            unityServer.StartServer().Returns(true);
            GameServer.Start(unityServer);
            unityServer.Received(1).StartServer();
            Assert.Throws <Exception>(() => GameServer.Start(unityServer));
        }
Example #31
0
        public void StartServer(string map, bool dedicated)
        {
            //	Disconnect!

            if (dedicated)
            {
                GameServer.Start(map, null);
            }
            else
            {
                if (GameServer.Start(map, null))
                {
                    GameClient.Connect("127.0.0.1", Network.Port);
                }
            }
        }
Example #32
0
 private static void Main()
 {
     try {
         Log.Info("Starting GameService...");
         SetConsoleConfigurations();
         SetNumberDecimalSeparator();
         GameServer.Kernel = new StandardKernel(new DepInjectionModule());
         GameServer server = GameServer.Kernel.Get <GameServer>();
         server.Start();
         Process.GetCurrentProcess().WaitForExit();
     }
     catch (Exception ex)
     {
         Console.WriteLine("EXCEPTION : " + ex.Message);
     }
 }
Example #33
0
        private static async Task PlayOnLAN(string[] args)
        {
            string server = null;
            int    port   = default;
            string option = string.Empty;

            if (args != null && args.Length <= 2 && args.Length > 0)
            {
                if (args.Length == 2)
                {
                    option = args[1].ToLower();
                }
                var parts = args[0].Split(":", 2);
                server = parts[0];
                port   = int.Parse(parts[1]);
            }

            ConsoleService.PrintTitle("Console Poker on LAN");
            if (option == string.Empty)
            {
                // TODO: Temporary, should clients be able to host their own servers?
                option = "c";

                // Console.WriteLine("(S)erver or (C)lient");
                // option = ConsoleService.TakeSpecificInputs(caseSensitive: false, "s", "c", "server", "client");
            }

            Console.Clear();
            switch (option)
            {
            case "s":
            case "server":
                ConsoleService.PrintTitle("Console Poker Server");
                var gameServer = new GameServer(port);
                gameServer.Start();
                Console.ReadLine();
                break;

            case "c":
            case "client":
                ConsoleService.PrintTitle("Console Poker Client");
                var gameClient = new GameClient();
                await gameClient.RunAsync(server, port);

                break;
            }
        }
Example #34
0
 static void Main(string[] args)
 {
     GameServer server = new GameServer();
     server.Start();
 }