Example #1
0
        public static void Main(string[] args)
        {
#if DEBUG
            _isDebug = true;
            Thread.Sleep(1000);
#endif
            CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo("en-US");
            Console.Title = $"OpenNos World Server{(_isDebug ? " Development Environment" : string.Empty)}";

            bool ignoreStartupMessages = false;
            _port = Convert.ToInt32(ConfigurationManager.AppSettings["WorldPort"]);
            int portArgIndex = Array.FindIndex(args, s => s == "--port");
            if (portArgIndex != -1 &&
                args.Length >= portArgIndex + 1 &&
                int.TryParse(args[portArgIndex + 1], out _port))
            {
                Console.WriteLine("Port override: " + _port);
            }
            foreach (string arg in args)
            {
                switch (arg)
                {
                case "--nomsg":
                    ignoreStartupMessages = true;
                    break;

                case "--notelemetry":
                    _ignoreTelemetry = true;
                    break;

                case "--h":
                case "--help":
                    Console.WriteLine("OpenNos Help v0.1");
                    Console.WriteLine("--port PORT_NUMBER - overrides the port of the server");
                    Console.WriteLine("--nomsg - disables the startup messages");
                    Console.WriteLine("--notelemetry - disables gathering of the crash data and sending to external server");
                    return;
                }
            }

            // initialize Logger
            Logger.InitializeLogger(LogManager.GetLogger(typeof(Program)));

            if (!ignoreStartupMessages)
            {
                Assembly        assembly        = Assembly.GetExecutingAssembly();
                FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location);
                string          text            = $"WORLD SERVER v{fileVersionInfo.ProductVersion}dev - PORT : {_port} by OpenNos Team";
                string          text2           =
                    $"Built on: {new DateTime(((fileVersionInfo.ProductBuildPart - 1) * TimeSpan.TicksPerDay) + (fileVersionInfo.ProductPrivatePart * TimeSpan.TicksPerSecond * 2)).AddYears(1999)}";
                string text3     = $"Built by: {BuildInfo.BuildUser}@{BuildInfo.BuildHost} ({BuildInfo.BuildOS})";
                int    offset    = (Console.WindowWidth / 2) + (text.Length / 2);
                int    offset2   = (Console.WindowWidth / 2) + (text2.Length / 2);
                int    offset3   = (Console.WindowWidth / 2) + (text3.Length / 2);
                string separator = new string('=', Console.WindowWidth);
                Console.WriteLine(separator + string.Format("{0," + offset + "}\n", text) +
                                  string.Format("{0," + offset2 + "}\n", text2) +
                                  string.Format("{0," + offset3 + "}\n", text3) + separator);
            }

            // initialize api
            string authKey = ConfigurationManager.AppSettings["MasterAuthKey"];
            if (CommunicationServiceClient.Instance.Authenticate(authKey))
            {
                Logger.Info(Language.Instance.GetMessageFromKey("API_INITIALIZED"));
            }

            // initialize DB
            if (DataAccessHelper.Initialize())
            {
                // initialilize maps
                ServerManager.Instance.Initialize();
            }
            else
            {
                Console.ReadKey();
                return;
            }

            PacketFacility.Initialize(typeof(EntryPointPacket));
            PacketFacility.Initialize(typeof(UseSkillPacket));
            PacketFacility.Initialize(typeof(BazaarBuyPacket));
            PacketFacility.Initialize(typeof(CreateFamilyPacket));
            PacketFacility.Initialize(typeof(DeleteItemPacket));
            PacketFacility.Initialize(typeof(MateControlPacket));
            PacketFacility.Initialize(typeof(MinilandAddObjectPacket));
            PacketFacility.Initialize(typeof(BuyPacket));
            PacketFacility.Initialize(typeof(EscapePacket));
            PacketFacility.Initialize(typeof(CClosePacket));
            PacketFacility.Initialize(typeof(HelpPacket));

            try
            {
                _exitHandler += ExitHandler;
                AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;
                if (CurrentOS.IsWindows)
                {
                    NativeMethods.SetConsoleCtrlHandler(_exitHandler, true);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("General Error", ex);
            }

            string ipAddress = ConfigurationManager.AppSettings["IPAddress"];
portloop:
            try
            {
                // ReSharper disable once ObjectCreationAsStatement
                new NetworkManager <WorldCryptography>(ipAddress, _port, typeof(LoginCryptography), true);
            }
            catch (SocketException ex)
            {
                if (ex.ErrorCode == 10048)
                {
                    _port++;
                    Logger.Info("Port already in use! Incrementing...");
                    goto portloop;
                }
                Logger.Error("General Error", ex);
                Environment.Exit(ex.ErrorCode);
            }

            ServerManager.Instance.ServerGroup = ConfigurationManager.AppSettings["ServerGroup"];
            int sessionLimit = ConfigurationServiceClient.Instance.GetSlotCount();
            int?newChannelId = CommunicationServiceClient.Instance.RegisterWorldServer(new SerializableWorldServer(ServerManager.Instance.WorldId, ipAddress, _port, sessionLimit, ServerManager.Instance.ServerGroup));
            if (newChannelId.HasValue)
            {
                ServerManager.Instance.ChannelId = newChannelId.Value;
                MailServiceClient.Instance.Authenticate(authKey, ServerManager.Instance.WorldId);
                ConfigurationServiceClient.Instance.Authenticate(authKey, ServerManager.Instance.WorldId);
                ServerManager.Instance.Configuration = ConfigurationServiceClient.Instance.GetConfigurationObject();
                if (ServerManager.Instance.Configuration.UseChatLogService && !ChatLogServiceClient.Instance.Authenticate(ConfigurationManager.AppSettings["ChatLogKey"]))
                {
                    throw new AuthenticationException();
                }
                if (ServerManager.Instance.Configuration.UseGameLogService)
                {
                    if (!GameLogger.InitializeLogger(ConfigurationManager.AppSettings["GameLogKey"]))
                    {
                        throw new AuthenticationException();
                    }
                }
                else
                {
                    GameLogger.InitializeLogger(null);
                }
                ServerManager.Instance.MallApi = new GameObject.Helpers.MallAPIHelper(ServerManager.Instance.Configuration.MallBaseUrl);
                if (ServerManager.Instance.Configuration.EnableAutoRestart)
                {
                    Observable.Interval(TimeSpan.FromMinutes(1)).Subscribe(x => ServerManager.Instance.AutoRestartProcess());
                }
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine($"[{DateTime.UtcNow.ToLongTimeString()}][MSG][Main]: Server running!");
                Console.ResetColor();
            }
            else
            {
                Logger.Error("Could not retrieve ChannelId from Web API.");
                Console.ReadKey();
            }
        }