public ServerSocket(int port)
        {
            _globalChatModel = new GlobalChat();
            AllChatDetails = new AllChatDetails();
            AllChatDetails.AddChat(_globalChatModel);

            Port = port;
            Listener = new TcpListener(Port);
        }
        public ServerSocket(int port, IContainerInterfaces containerInterfaces)
        {
            _containerInterfaces = containerInterfaces;
            _globalChatModel     = new GlobalChat();
            AllChatDetails       = new AllChatDetails();
            AllChatDetails.AddChat(_globalChatModel);

            Port     = port;
            Listener = new TcpListener(Port);
        }
Exemple #3
0
        public Server(IPAddress addr, ushort port)
        {
            if (Program.Taskbar != null)
                Program.Taskbar.SetProgressState(TaskbarProgressBarState.Indeterminate);
            ScriptHost = ScriptHost.Create();

            socket = new TcpListener(addr, port);
            Program.Logger.LogInfo(String.Format("Listening on {0}:{1}", addr, port));
            thread = new Thread(AcceptClients);

            pingTimer = new Timer(new TimerCallback(this.PingClients), new AutoResetEvent(false), 60000, 60000);
            npcRespawnTimer = new Timer(new TimerCallback(this.RespawnNPCs), new AutoResetEvent(false), 2000, 1000);

            Database = new Database("eoserv.db4o");
            Program.Logger.LogSuccess("Database loaded.");
            Global = new GlobalChat();
            clients = new Dictionary<ushort, IClient>();
            maps = new Dictionary<ushort, IMap>();
            characters = new List<Character>();

            ItemData = new EIF("./data/dat001.eif");
            Program.Logger.LogSuccess(String.Format("Loaded {0} items.", ItemData.Count));
            NpcData = new ENF("./data/dtn001.enf");
            Program.Logger.LogSuccess(String.Format("Loaded {0} NPCs.", NpcData.Count));
            ClassData = new ECF("./data/dat001.ecf");
            Program.Logger.LogSuccess(String.Format("Loaded {0} classes.", ClassData.Count));
            SpellData = new ESF("./data/dsl001.esf");
            Program.Logger.LogSuccess(String.Format("Loaded {0} spells.", SpellData.Count));
            MapData = new MapDataSet("./data/maps/");
            Program.Logger.LogSuccess(String.Format("Loaded {0} maps.", MapData.Count));

            /*ItemData.GetPubFile("./tmp/");
            NpcData.GetPubFile("./tmp/");
            ClassData.GetPubFile("./tmp/");
            SpellData.GetPubFile("./tmp/");*/

            foreach (KeyValuePair<ushort, MapData> entry in MapData)
            {
                entry.Value.GetPubFile("./tmp/");
                maps.Add(entry.Key, new Map(entry.Value));
                maps[entry.Key].SpawnNpcs(this);
            }

            if (Program.Taskbar != null)
                Program.Taskbar.SetProgressState(TaskbarProgressBarState.NoProgress);

            slnClient = new SLNClient();
            consoleInput = new ConsoleInput(this);

            Program.Logger.LogSuccess("Server started");
        }
        public async Task <IActionResult> GlobalMessagePost(int id, [FromForm] string message)
        {
            GlobalChat NewMessage = new GlobalChat();

            NewMessage.PlayerId = id;
            NewMessage.Message  = Request.Form["NewGlobalMessage"];


            await _db.GlobalChat.AddAsync(NewMessage);

            await _db.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
Exemple #5
0
        public async Task <bool> SaveChatRecord(GlobalChatDto chatDto)
        {
            // convert string to int
            var temp   = chatDto.Username;
            var userId = Convert.ToInt32(temp);

            var team = await _context.Teams.FirstOrDefaultAsync(x => x.UserId == userId);

            GlobalChat chatRecord = new GlobalChat
            {
                ChatText = chatDto.ChatText,
                Username = team.Mascot,
                ChatTime = chatDto.ChatTime
            };

            await _context.GlobalChats.AddAsync(chatRecord);

            return(await _context.SaveChangesAsync() > 0);
        }
        /// <summary>
        /// Inits this instance.
        /// </summary>
        public static void Init()
        {
            Running = true;

            Logger.WriteLog("--------- Server Started at " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + " ---------");
            Logger.Log("Debug mode started", LogType.Debug);
            //TODO Add debug messages
            //TODO load the level if it exists
            Block.InIt();
            Logger.Log("Starting update timer", LogType.Debug);
            UpdateTimer = new System.Threading.Timer((e) => Update(), null, 0, 100);
            Logger.Log("Log timer started", LogType.Debug);
            Logger.Log("Loading DLL's", LogType.Debug);
            LoadAllDlls.Init();
            Logger.Log("Finished loading DLL's", LogType.Debug);
            Logger.Log("Sending Heartbeat..", LogType.Debug);
            Logger.Log("Auto-Updater Starting..", LogType.Debug);
            Updater.InIt();
            HeartThread = new Thread(new ThreadStart(Heartbeat.ActivateHeartBeat));
            HeartThread.Start();
            Logger.Log("Starting Physics Tick..", LogType.Debug);
            PhysicsBlock.InIt();
            CmdReloadCmds reload = new CmdReloadCmds();

            reload.Initialize();

            Groups.PlayerGroup.Load();
            VerifyGroup = Groups.PlayerGroup.Find(ServerSettings.GetSetting("VerifyGroup"));
            Mainlevel   = Level.LoadLevel(ServerSettings.GetSetting("Main-Level"));
            if (Mainlevel == null)
            {
                Mainlevel = Level.CreateLevel(new Vector3S(256, 128, 64), Level.LevelTypes.Flat);
                ServerSettings.SetSetting("Main-Level", null, "main");
            }
            Level.Levels.Add(Mainlevel);
            if (ServerSettings.GetSettingBoolean("LoadAllLevels"))
            {
                Level.LoadAllLevels();
            }
            BlockQueue.Start();
            Backup.StartBackup();

            Database.Init();

            CreateCoreFiles();

            InternetUtils = new InetUtils();
            InetUtils.InternetAvailable = InetUtils.CanConnectToInternet();

            Logger.Log("Loading Bans", LogType.Debug);
            Logger.Log("IPBANS", LogType.Debug);
            IPBans = new List <string>(File.ReadAllLines("bans/IPBans.txt"));
            Logger.Log("IPBANS", LogType.Debug);
            UsernameBans = new List <string>(File.ReadAllLines("bans/NameBans.txt"));
            StartListening();
            Started = true;

            if (OnServerFinishSetup != null)
            {
                OnServerFinishSetup();
            }
            blockThread = new Thread(new ThreadStart(delegate
            {
                while (true)
                {
                    Thread.Sleep(60000);
                    Level.Levels.ForEach(delegate(Level l)
                    {
                        try
                        {
                            l.SaveToBinary();
                        }
                        catch (Exception e)
                        {
                            Logger.LogError(e);
                        }
                    });
                }
            }));
            blockThread.Start();
            Logger.Log("[Important]: Server Started.", Color.Black, Color.White);
            if (!ServerSettings.GetSettingBoolean("VerifyNames"))
            {
                Logger.Log("[Important]: The server is running with verify names off! This could lead to bad things! Please turn on verify names if you dont know the risk and dont want these bad things to happen!", LogType.Critical);
            }

            if (ServerSettings.GetSettingBoolean("IRC-Enabled"))
            {
                try
                {
                    IRC = new ServerChat();
                    IRC.Connect();
                }
                catch (Exception e)
                {
                    Logger.LogError(e);
                }
            }

            if (ServerSettings.GetSettingBoolean("GC-Enabled"))
            {
                GC = new GlobalChat();
                try
                {
                    GC.Connect();
                }
                catch (Exception e)
                {
                    Logger.LogError(e);
                }
            }

            try
            {
                RC = new ConsoleListener();
                RC.Start();
            }
            catch { }

            PlayerConnectionTimeoutChecker = new Thread(() => {
                int sleep = ServerSettings.GetSettingInt("AutoTimeout");
                if (sleep < 0)
                {
                    sleep = 30;
                }
                if (sleep != 0)
                {
                    while (Running)
                    {
                        for (int i = 0; i < sleep && Running; i++)
                        {
                            Thread.Sleep(1000);
                        }
                        if (!Running)
                        {
                            break;
                        }
                        foreach (Player p in Players)
                        {
                            if (p.lastReceived.AddSeconds(sleep) < DateTime.Now)
                            {
#if !DEBUG
                                p.Kick("The connection timed out");
#endif
                            }
                        }
                    }
                }
            });
            PlayerConnectionTimeoutChecker.Start();
        }
Exemple #7
0
        internal static void Initialize(Arguments args)
        {
            Console.WriteLine("Platform is {0}", Platform.CurrentPlatform);

            // Special case handling of Game.Mod argument: if it matches a real filesystem path
            // then we use this to override the mod search path, and replace it with the mod id
            var    modArgument   = args.GetValue("Game.Mod", null);
            string customModPath = null;

            if (modArgument != null && (File.Exists(modArgument) || Directory.Exists(modArgument)))
            {
                customModPath = modArgument;
                args.ReplaceValue("Game.Mod", Path.GetFileNameWithoutExtension(modArgument));
            }

            InitializeSettings(args);

            Log.AddChannel("perf", "perf.log");
            Log.AddChannel("debug", "debug.log");
            Log.AddChannel("server", "server.log");
            Log.AddChannel("sound", "sound.log");
            Log.AddChannel("graphics", "graphics.log");
            Log.AddChannel("geoip", "geoip.log");
            Log.AddChannel("irc", "irc.log");
            Log.AddChannel("nat", "nat.log");

            var platforms = new[] { Settings.Game.Platform, "Default", null };

            foreach (var p in platforms)
            {
                if (p == null)
                {
                    throw new InvalidOperationException("Failed to initialize platform-integration library. Check graphics.log for details.");
                }

                Settings.Game.Platform = p;
                try
                {
                    var rendererPath = Platform.ResolvePath(Path.Combine(".", "OpenRA.Platforms." + p + ".dll"));
                    var assembly     = Assembly.LoadFile(rendererPath);

                    var platformType = assembly.GetTypes().SingleOrDefault(t => typeof(IPlatform).IsAssignableFrom(t));
                    if (platformType == null)
                    {
                        throw new InvalidOperationException("Platform dll must include exactly one IPlatform implementation.");
                    }

                    var platform = (IPlatform)platformType.GetConstructor(Type.EmptyTypes).Invoke(null);
                    Renderer = new Renderer(platform, Settings.Graphics);
                    Sound    = new Sound(platform, Settings.Sound);

                    break;
                }
                catch (Exception e)
                {
                    Log.Write("graphics", "{0}", e);
                    Console.WriteLine("Renderer initialization failed. Check graphics.log for details.");

                    if (Renderer != null)
                    {
                        Renderer.Dispose();
                    }

                    if (Sound != null)
                    {
                        Sound.Dispose();
                    }
                }
            }

            GeoIP.Initialize();

            if (!Settings.Server.DiscoverNatDevices)
            {
                Settings.Server.AllowPortForward = false;
            }
            else
            {
                discoverNat = UPnP.DiscoverNatDevices(Settings.Server.NatDiscoveryTimeout);
                Settings.Server.AllowPortForward = true;
            }

            GlobalChat = new GlobalChat();

            Mods = new InstalledMods(customModPath);
            Console.WriteLine("Available mods:");
            foreach (var mod in Mods)
            {
                Console.WriteLine("\t{0}: {1} ({2})", mod.Key, mod.Value.Metadata.Title, mod.Value.Metadata.Version);
            }

            InitializeMod(Settings.Game.Mod, args);
        }
Exemple #8
0
        internal static void Initialize(Arguments args)
        {
            Console.WriteLine("Platform is {0}", Platform.CurrentPlatform);

            InitializeSettings(args);

            Log.AddChannel("perf", "perf.log");
            Log.AddChannel("debug", "debug.log");
            Log.AddChannel("sync", "syncreport.log");
            Log.AddChannel("server", "server.log");
            Log.AddChannel("sound", "sound.log");
            Log.AddChannel("graphics", "graphics.log");
            Log.AddChannel("geoip", "geoip.log");
            Log.AddChannel("irc", "irc.log");

            if (Settings.Server.DiscoverNatDevices)
            {
                UPnP.TryNatDiscovery();
            }
            else
            {
                Settings.Server.NatDeviceAvailable = false;
                Settings.Server.AllowPortForward   = false;
            }

            GeoIP.Initialize();

            var renderers = new[] { Settings.Graphics.Renderer, "Default", null };

            foreach (var r in renderers)
            {
                if (r == null)
                {
                    throw new InvalidOperationException("No suitable renderers were found. Check graphics.log for details.");
                }

                Settings.Graphics.Renderer = r;
                try
                {
                    Renderer = new Renderer(Settings.Graphics, Settings.Server);
                    break;
                }
                catch (Exception e)
                {
                    Log.Write("graphics", "{0}", e);
                    Console.WriteLine("Renderer initialization failed. Fallback in place. Check graphics.log for details.");
                }
            }

            Sound = new Sound(Settings.Sound.Engine);

            GlobalChat = new GlobalChat();

            Console.WriteLine("Available mods:");
            foreach (var mod in ModMetadata.AllMods)
            {
                Console.WriteLine("\t{0}: {1} ({2})", mod.Key, mod.Value.Title, mod.Value.Version);
            }

            InitializeMod(Settings.Game.Mod, args);

            if (Settings.Server.DiscoverNatDevices)
            {
                RunAfterDelay(Settings.Server.NatDiscoveryTimeout, UPnP.StoppingNatDiscovery);
            }
        }
Exemple #9
0
        internal static void Initialize(Arguments args)
        {
            Console.WriteLine("Platform is {0}", Platform.CurrentPlatform);

            InitializeSettings(args);

            Log.AddChannel("perf", "perf.log");
            Log.AddChannel("debug", "debug.log");
            Log.AddChannel("sync", "syncreport.log");
            Log.AddChannel("server", "server.log");
            Log.AddChannel("sound", "sound.log");
            Log.AddChannel("graphics", "graphics.log");
            Log.AddChannel("geoip", "geoip.log");
            Log.AddChannel("irc", "irc.log");
            Log.AddChannel("nat", "nat.log");

            var platforms = new[] { Settings.Game.Platform, "Default", null };

            foreach (var p in platforms)
            {
                if (p == null)
                {
                    throw new InvalidOperationException("Failed to initialize platform-integration library. Check graphics.log for details.");
                }

                Settings.Game.Platform = p;
                try
                {
                    var rendererPath = Platform.ResolvePath(Path.Combine(".", "OpenRA.Platforms." + p + ".dll"));
                    var assembly     = Assembly.LoadFile(rendererPath);

                    var platformType = assembly.GetTypes().SingleOrDefault(t => typeof(IPlatform).IsAssignableFrom(t));
                    if (platformType == null)
                    {
                        throw new InvalidOperationException("Platform dll must include exactly one IPlatform implementation.");
                    }

                    var platform = (IPlatform)platformType.GetConstructor(Type.EmptyTypes).Invoke(null);
                    Renderer = new Renderer(platform, Settings.Graphics);
                    Sound    = new Sound(platform, Settings.Sound);

                    break;
                }
                catch (Exception e)
                {
                    Log.Write("graphics", "{0}", e);
                    Console.WriteLine("Renderer initialization failed. Check graphics.log for details.");

                    if (Renderer != null)
                    {
                        Renderer.Dispose();
                    }

                    if (Sound != null)
                    {
                        Sound.Dispose();
                    }
                }
            }

            GeoIP.Initialize();

            if (!Game.Settings.Server.DiscoverNatDevices)
            {
                Game.Settings.Server.AllowPortForward = false;
            }
            else
            {
                discoverNat = UPnP.DiscoverNatDevices(Settings.Server.NatDiscoveryTimeout);
                Game.Settings.Server.AllowPortForward = true;
            }

            GlobalChat = new GlobalChat();

            Console.WriteLine("Available mods:");
            foreach (var mod in ModMetadata.AllMods)
            {
                Console.WriteLine("\t{0}: {1} ({2})", mod.Key, mod.Value.Title, mod.Value.Version);
            }

            InitializeMod(Settings.Game.Mod, args);
        }
        internal static void Initialize(Arguments args)
        {
            Console.WriteLine("Platform is {0}", Platform.CurrentPlatform);

            // Load the engine version as early as possible so it can be written to exception logs
            try
            {
                EngineVersion = File.ReadAllText(Platform.ResolvePath(Path.Combine(".", "VERSION"))).Trim();
            }
            catch { }

            if (string.IsNullOrEmpty(EngineVersion))
            {
                EngineVersion = "Unknown";
            }

            Console.WriteLine("Engine version is {0}", EngineVersion);

            // Special case handling of Game.Mod argument: if it matches a real filesystem path
            // then we use this to override the mod search path, and replace it with the mod id
            var modID            = args.GetValue("Game.Mod", null);
            var explicitModPaths = new string[0];

            if (modID != null && (File.Exists(modID) || Directory.Exists(modID)))
            {
                explicitModPaths = new[] { modID };
                modID            = Path.GetFileNameWithoutExtension(modID);
            }

            InitializeSettings(args);

            Log.AddChannel("perf", "perf.log");
            Log.AddChannel("debug", "debug.log");
            Log.AddChannel("server", "server.log");
            Log.AddChannel("sound", "sound.log");
            Log.AddChannel("graphics", "graphics.log");
            Log.AddChannel("geoip", "geoip.log");
            Log.AddChannel("irc", "irc.log");
            Log.AddChannel("nat", "nat.log");

            var platforms = new[] { Settings.Game.Platform, "Default", null };

            foreach (var p in platforms)
            {
                if (p == null)
                {
                    throw new InvalidOperationException("Failed to initialize platform-integration library. Check graphics.log for details.");
                }

                Settings.Game.Platform = p;
                try
                {
                    var rendererPath = Platform.ResolvePath(Path.Combine(".", "OpenRA.Platforms." + p + ".dll"));
                    var assembly     = Assembly.LoadFile(rendererPath);

                    var platformType = assembly.GetTypes().SingleOrDefault(t => typeof(IPlatform).IsAssignableFrom(t));
                    if (platformType == null)
                    {
                        throw new InvalidOperationException("Platform dll must include exactly one IPlatform implementation.");
                    }

                    var platform = (IPlatform)platformType.GetConstructor(Type.EmptyTypes).Invoke(null);
                    Renderer = new Renderer(platform, Settings.Graphics);
                    Sound    = new Sound(platform, Settings.Sound);

                    break;
                }
                catch (Exception e)
                {
                    Log.Write("graphics", "{0}", e);
                    Console.WriteLine("Renderer initialization failed. Check graphics.log for details.");

                    if (Renderer != null)
                    {
                        Renderer.Dispose();
                    }

                    if (Sound != null)
                    {
                        Sound.Dispose();
                    }
                }
            }

            GeoIP.Initialize();

            if (!Settings.Server.DiscoverNatDevices)
            {
                Settings.Server.AllowPortForward = false;
            }
            else
            {
                discoverNat = UPnP.DiscoverNatDevices(Settings.Server.NatDiscoveryTimeout);
                Settings.Server.AllowPortForward = true;
            }

            GlobalChat = new GlobalChat();

            var modSearchArg   = args.GetValue("Engine.ModSearchPaths", null);
            var modSearchPaths = modSearchArg != null?
                                 FieldLoader.GetValue <string[]>("Engine.ModsPath", modSearchArg) :
                                     new[] { Path.Combine(".", "mods") };

            Mods = new InstalledMods(modSearchPaths, explicitModPaths);
            Console.WriteLine("Internal mods:");
            foreach (var mod in Mods)
            {
                Console.WriteLine("\t{0}: {1} ({2})", mod.Key, mod.Value.Metadata.Title, mod.Value.Metadata.Version);
            }

            ExternalMods = new ExternalMods();

            Manifest currentMod;

            if (modID != null && Mods.TryGetValue(modID, out currentMod))
            {
                var launchPath = args.GetValue("Engine.LaunchPath", Assembly.GetEntryAssembly().Location);

                // Sanitize input from platform-specific launchers
                // Process.Start requires paths to not be quoted, even if they contain spaces
                if (launchPath.First() == '"' && launchPath.Last() == '"')
                {
                    launchPath = launchPath.Substring(1, launchPath.Length - 2);
                }

                ExternalMods.Register(Mods[modID], launchPath, ModRegistration.User);

                ExternalMod activeMod;
                if (ExternalMods.TryGetValue(ExternalMod.MakeKey(Mods[modID]), out activeMod))
                {
                    ExternalMods.ClearInvalidRegistrations(activeMod, ModRegistration.User);
                }
            }

            Console.WriteLine("External mods:");
            foreach (var mod in ExternalMods)
            {
                Console.WriteLine("\t{0}: {1} ({2})", mod.Key, mod.Value.Title, mod.Value.Version);
            }

            InitializeMod(modID, args);
        }