public void NPServer09_GetCustomContract() { string PipeName = "Test"; string VerifyMessage = "TestMessage"; Assert.IsFalse(NPServer.IsNamedPipeOpen(PipeName)); NPServer Server = new NPServer(PipeName, VerifyMessage); CustomContract FromServer = new CustomContract() { Key = "This is Custom", Value = "Custom Value" }; Server.UpdateCommand("Custom", args => { return(FromServer); }); Server.Start(); Assert.AreEqual(Server.IsRunning, true); Assert.IsTrue(NPServer.IsNamedPipeOpen(PipeName)); NPClient Client = new NPClient(Environment.MachineName, PipeName, VerifyMessage); CustomContract result = Client.Get <CustomContract>("Custom"); Assert.AreEqual(result, FromServer); Server.Stop().Wait(); Server.Dispose(); Assert.AreEqual(Server.IsRunning, false); Assert.IsFalse(NPServer.IsNamedPipeOpen(PipeName)); }
public void NPServer07_ClientMissing() { string PipeName = "Test"; string VerifyMessage = "TestMessage"; Assert.IsFalse(NPServer.IsNamedPipeOpen(PipeName)); NPClient Client = new NPClient(PipeName, VerifyMessage); bool MissingMethodException = false; try { Client.Get("Fedfe"); } catch (TimeoutException) { MissingMethodException = true; } Assert.IsTrue(MissingMethodException); NPServer Server = new NPServer(PipeName, VerifyMessage); Server.UpdateCommand("Fedfe", args => { return("Arabe"); }); Server.Start(); Assert.AreEqual(Server.IsRunning, true); Assert.IsTrue(NPServer.IsNamedPipeOpen(PipeName)); Assert.AreEqual(Client.Get("Fedfe"), "Arabe"); Server.Stop().Wait(); Server.Dispose(); Assert.AreEqual(Server.IsRunning, false); Assert.IsFalse(NPServer.IsNamedPipeOpen(PipeName)); }
public void NPServer05_VerifyMessageIncurrect() { Trace.WriteLine("NPServer05_VerifyMessageIncurrect " + Counter++.ToString()); string PipeName = "Test"; string VerifyMessage = "TestMessage"; string VerifyFailMessage = "ArabeMessage"; Assert.IsFalse(NPServer.IsNamedPipeOpen(PipeName)); using (NPServer Server = new NPServer(PipeName, VerifyMessage)) { Server.Start(); Assert.AreEqual(Server.IsRunning, true); NPClient Client = new NPClient(PipeName, VerifyFailMessage); bool UnauthorizedAccessException = false; try { Client.Get("Fedfe"); } catch (UnauthorizedAccessException) { UnauthorizedAccessException = true; } Assert.IsTrue(UnauthorizedAccessException); Server.Stop().Wait(); } Assert.IsFalse(NPServer.IsNamedPipeOpen(PipeName)); Trace.WriteLine("END NPServer05_VerifyMessageIncurrect " + Counter++.ToString()); }
public void NPServer06_RemoveCommand() { Trace.WriteLine("NPServer06_RemoveCommand " + Counter++.ToString()); string PipeName = "Test"; string VerifyMessage = "TestMessage"; Assert.IsFalse(NPServer.IsNamedPipeOpen(PipeName)); using (NPServer Server = new NPServer(PipeName, VerifyMessage)) { Server.UpdateCommand("Arabe", args => { return("Fedfe"); }); Server.UpdateCommand("ONE", args => { return("1"); }); Server.Start(); Assert.AreEqual(Server.IsRunning, true); NPClient Client = new NPClient(PipeName, VerifyMessage); Assert.AreEqual(Client.Get("Arabe"), "Fedfe"); Assert.AreEqual(Client.Get("ONE"), "1"); Server.RemoveCommand("ONE"); bool MissingMethodException = false; try { Client.Get("ONE"); } catch (MissingMethodException) { MissingMethodException = true; } Assert.IsTrue(MissingMethodException); } Assert.IsFalse(NPServer.IsNamedPipeOpen(PipeName)); Trace.WriteLine("END NPServer06_RemoveCommand " + Counter++.ToString()); }
public void NPServer03_Command() { Trace.WriteLine("NPServer03_Command " + Counter++.ToString()); string PipeName = "Test"; string VerifyMessage = "TestMessage"; Assert.IsFalse(NPServer.IsNamedPipeOpen(PipeName)); using (NPServer Server = new NPServer(PipeName, VerifyMessage)) { Server.UpdateCommand("3Arabe", args => { return("Fedfe"); }); Server.UpdateCommand("3ONE", args => { return("1"); }); Server.UpdateCommand("3Thai", args => { return("ไทย"); }); Server.UpdateCommand("3ไทย", args => { return("Thai ไทย"); }); Assert.IsFalse(NPServer.IsNamedPipeOpen(PipeName)); Server.Start(); Assert.AreEqual(Server.IsRunning, true); Assert.IsTrue(NPServer.IsNamedPipeOpen(PipeName)); NPClient Client = new NPClient(PipeName, VerifyMessage); Assert.AreEqual(Client.Get("3Arabe"), "Fedfe"); Assert.AreEqual(Server.IsRunning, true); Assert.AreEqual(Client.Get("3ONE"), "1"); Assert.AreEqual(Server.IsRunning, true); Assert.AreEqual(Client.Get("3Thai"), "ไทย"); Assert.AreEqual(Server.IsRunning, true); Assert.AreEqual(Client.Get("3ไทย"), "Thai ไทย"); Assert.AreEqual(Server.IsRunning, true); //Update command Server.UpdateCommand("3ONE", (o) => { return("New ONE"); }); Assert.AreEqual(Client.Get("3ONE"), "New ONE"); Assert.AreEqual(Server.IsRunning, true); Server.Stop().Wait(); Assert.AreEqual(Server.IsRunning, false); Assert.IsFalse(NPServer.IsNamedPipeOpen(PipeName)); } Trace.WriteLine("END NPServer03_Command " + Counter++.ToString()); }
public void NPServer10_GetWithArgs() { string PipeName = "Test"; string VerifyMessage = "TestMessage"; Assert.IsFalse(NPServer.IsNamedPipeOpen(PipeName)); NPServer Server = new NPServer(PipeName, VerifyMessage); Server.UpdateCommand("Add", args => { int First = NPConvertor.ToInt(args[0]); int Second = NPConvertor.ToInt(args[1]); return(First + Second); }); Server.UpdateCommand("Custom", args => { string KEY = NPConvertor.ToString(args[0]); string VALUE = NPConvertor.ToString(args[1]); CustomContract custom = NPConvertor.To <CustomContract>(args[2]); return(custom.Key == KEY && custom.Value == VALUE); }); Server.Start(); NPClient Client = new NPClient(Environment.MachineName, PipeName, VerifyMessage); Assert.AreEqual(Client.Get <int>("Add", 1, 2), 3); Assert.IsFalse(Client.Get <bool>("Custom", "YES", "SIR", new CustomContract() { Key = "YES", Value = "ARABE" })); Assert.IsTrue(Client.Get <bool>("Custom", "YES", "SIR", new CustomContract() { Key = "YES", Value = "SIR" })); Server.Stop().Wait(); Server.Dispose(); Assert.AreEqual(Server.IsRunning, false); Assert.IsFalse(NPServer.IsNamedPipeOpen(PipeName)); }
public void NPServer08_Networking() { string PipeName = "Test"; string VerifyMessage = "TestMessage"; Assert.IsFalse(NPServer.IsNamedPipeOpen(PipeName)); NPServer Server = new NPServer(PipeName, VerifyMessage); Server.UpdateCommand("Fedfe", args => { return("Arabe"); }); Server.Start(); Assert.AreEqual(Server.IsRunning, true); Assert.IsTrue(NPServer.IsNamedPipeOpen(PipeName)); NPClient Client = new NPClient(Environment.MachineName, PipeName, VerifyMessage); Assert.AreEqual(Client.Get("Fedfe"), "Arabe"); Server.Stop().Wait(); Server.Dispose(); Assert.AreEqual(Server.IsRunning, false); Assert.IsFalse(NPServer.IsNamedPipeOpen(PipeName)); }
public GameServer(Configuration config, Resources.ResourceManager resManager, Commands.CommandManager commandManager, NPClient platformClient) { m_configuration = config; commandManager.SetGameServer(this); CommandManager = commandManager; m_resourceManager = resManager; m_resourceManager.SetGameServer(this); m_platformClient = platformClient; var dnsEntry = Dns.GetHostEntry("refint.org"); foreach (var address in dnsEntry.AddressList) { if (address.AddressFamily == AddressFamily.InterNetwork) { m_serverList = new IPEndPoint(address, 30110); } } UseAsync = true; }
public GameServer(Configuration config, Resources.ResourceManager resManager, Commands.CommandManager commandManager, NPClient platformClient) { m_configuration = config; commandManager.SetGameServer(this); CommandManager = commandManager; m_resourceManager = resManager; m_resourceManager.SetGameServer(this); m_platformClient = platformClient; var dnsEntry = Dns.GetHostEntry("refint.org"); foreach (var address in dnsEntry.AddressList) { if (address.AddressFamily == AddressFamily.InterNetwork) { m_serverList = new IPEndPoint(address, 30110); } } UseAsync = true; }
public NP2HTTPUserFileHandler(NPClient np) { _np = np; _log = LogManager.GetLogger(GetType()); }
public void NPServer11_NodeHub() { string PipeName = "Test"; string VerifyMessage = "TestMessage"; Assert.IsFalse(NPServer.IsNamedPipeOpen(PipeName)); NPServer Server = new NPServer(PipeName, VerifyMessage); string ServerName = "Arabe"; int ServerNumber = 1; Server.Sync("Name", ServerName); Server.Sync("Number", ServerNumber); Server.Start(); NPClient Client = new NPClient(PipeName, VerifyMessage); string ClientName = default(string); int ClientNumber = default(int); Client.Subscribe <string>("Name", v => { ClientName = v; }); Client.Subscribe <int>("Number", v => ClientNumber = v); Task.Delay(100).Wait(); //Test First Subscribe Data Assert.AreEqual(ClientName, ServerName); //Arabe = Arabe Assert.AreEqual(ClientNumber, ServerNumber); //1 = 1 string ServerName2 = "Fedfe"; int ServerNumber2 = 2; Server.Sync("Name", ServerName2); Server.Sync("Number", ServerNumber2); Task.Delay(100).Wait(); //Test First Change Data Assert.AreEqual(ClientName, ServerName2); //Fedfe = Fedfe Assert.AreEqual(ClientNumber, ServerNumber2); //2 = 2 Client.Unsubscribe("Number"); Task.Delay(100).Wait(); string ServerName3 = "Yes Sir"; Server.Sync("Name", ServerName3); Task.Delay(100).Wait(); Server.Sync("Number", 3); Assert.AreEqual(ClientName, ServerName3); //Yes Sir = Yes Sir Assert.AreEqual(ClientNumber, ServerNumber2); //2 = 2 Client.Unsubscribe("Name"); Server.Sync("Name", "NotThings"); Assert.AreEqual(ClientName, ServerName3); //Yes Sir = Yes Sir Server.Stop().Wait(); Server.Dispose(); Assert.AreEqual(Server.IsRunning, false); Assert.IsFalse(NPServer.IsNamedPipeOpen(PipeName)); }
private static void Main(string[] args) { // log4net setup if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX) { var appender = new ConsoleAppender { #if DEBUG Threshold = Level.Debug, #else Threshold = Level.Info, #endif Layout = new PatternLayout("<%d{HH:mm:ss}> [%logger:%thread] %level: %message%newline"), }; BasicConfigurator.Configure(new IAppender[] { appender, new DebugAppender { Layout = appender.Layout, Threshold = Level.All } }); } else { var appender = new ColoredConsoleAppender { #if DEBUG Threshold = Level.Debug, #else Threshold = Level.Info, #endif Layout = new PatternLayout("<%d{HH:mm:ss}> [%logger:%thread] %level: %message%newline"), }; appender.AddMapping(new ColoredConsoleAppender.LevelColors { Level = Level.Debug, ForeColor = ColoredConsoleAppender.Colors.Cyan | ColoredConsoleAppender.Colors.HighIntensity }); appender.AddMapping(new ColoredConsoleAppender.LevelColors { Level = Level.Info, ForeColor = ColoredConsoleAppender.Colors.Green | ColoredConsoleAppender.Colors.HighIntensity }); appender.AddMapping(new ColoredConsoleAppender.LevelColors { Level = Level.Warn, ForeColor = ColoredConsoleAppender.Colors.Purple | ColoredConsoleAppender.Colors.HighIntensity }); appender.AddMapping(new ColoredConsoleAppender.LevelColors { Level = Level.Error, ForeColor = ColoredConsoleAppender.Colors.Red | ColoredConsoleAppender.Colors.HighIntensity }); appender.AddMapping(new ColoredConsoleAppender.LevelColors { Level = Level.Fatal, ForeColor = ColoredConsoleAppender.Colors.White | ColoredConsoleAppender.Colors.HighIntensity, BackColor = ColoredConsoleAppender.Colors.Red }); appender.ActivateOptions(); BasicConfigurator.Configure(new IAppender[] { appender, new DebugAppender { Layout = appender.Layout, Threshold = Level.All } }); } var log = LogManager.GetLogger("Main"); // Arguments if (args.Length < 4) { log.ErrorFormat("Needs 4 arguments: hostname port username password"); return; } var hostname = args[0]; var port = ushort.Parse(args[1]); var username = args[2]; var password = args[3]; // NP connection setup log.DebugFormat("Connecting to {0}:{1}...", hostname, port); var np = new NPClient(hostname, port); if (!np.Connect()) { log.Error("Connection to NP server failed."); return; } // Get session token var ah = new SessionAuthenticationClient(hostname); try { ah.Authenticate(username, password); } catch (Exception err) { np.Disconnect(); #if DEBUG log.ErrorFormat("Could not authenticate: {0}", err); #else log.ErrorFormat("Could not authenticate: {0}", err.Message); #endif return; } // Validate authentication using session token try { np.AuthenticateWithToken(ah.SessionToken).Wait(); } catch (Exception err) { #if DEBUG log.ErrorFormat("Authenticated but session token was invalid. {0}", err); #else log.ErrorFormat("Authenticated but session token was invalid ({0}).", err.Message); #endif return; } try { log.InfoFormat("Server says: {0}", Encoding.UTF8.GetString(np.GetPublisherFile("motd-english.txt").Result)); np.Disconnect(); } catch { log.ErrorFormat("Could not read MOTD from NP server."); } }
private async Task Start(string configFileName) { Configuration config; try { config = Configuration.Load(configFileName ?? "citmp-server.yml"); // if running on WinNT default to using windowed logger if (Environment.OSVersion.Platform == PlatformID.Win32NT && !config.DisableWindowedLogger) { WindowedLogger.Initialize(config.DebugLog); } if (config.AutoStartResources == null) { this.Log().Fatal("No auto-started resources were configured."); return; } if (config.ListenPort == 0) { this.Log().Fatal("No port was configured."); return; } if (config.Downloads == null) { config.Downloads = new Dictionary <string, DownloadConfiguration>(); } } catch (System.IO.IOException) { this.Log().Fatal("Could not open the configuration file {0}.", configFileName ?? "citmp-server.yml"); return; } var platformServer = config.PlatformServer ?? "iv-platform.prod.citizen.re"; var client = new NPClient(platformServer, (config.PlatformPort == 0) ? (ushort)3036 : (ushort)config.PlatformPort); this.Log().Info("Connecting to Terminal platform server at {0}.", platformServer); var connectResult = client.Connect(); if (!connectResult) { this.Log().Fatal("Could not connect to the configured platform server ({0}).", platformServer); return; } this.Log().Info("Authenticating to Terminal with anonymous license key."); // authenticate anonymously var task = client.AuthenticateWithLicenseKey(""); if (!task.Wait(15000)) { this.Log().Fatal("Could not authenticate anonymously to the configured platform server ({0}) - operation timed out.", platformServer); return; } if (!task.Result) { this.Log().Fatal("Could not authenticate anonymously to the configured platform server ({0}).", platformServer); return; } this.Log().Info("Creating initial server instance."); var commandManager = new Commands.CommandManager(); var resManager = new Resources.ResourceManager(config); // create the game server (as resource scanning needs it now) var gameServer = new Game.GameServer(config, resManager, commandManager, client); // preparse resources if (config.PreParseResources != null) { this.Log().Info("Pre-parsing resources: {0}", string.Join(", ", config.PreParseResources)); foreach (var resource in config.PreParseResources) { resManager.ScanResources("resources/", resource); var res = resManager.GetResource(resource); if (res != null) { await res.Start(); } } } else { this.Log().Warn("No PreParseResources defined. This usually means you're using an outdated configuration file. Please consider this."); } // scan resources resManager.ScanResources("resources/"); // start the game server gameServer.Start(); // and initialize the HTTP server var httpServer = new HTTP.HttpServer(config, resManager); httpServer.Start(); // start resources foreach (var resource in config.AutoStartResources) { var res = resManager.GetResource(resource); if (res == null) { this.Log().Error("Could not find auto-started resource {0}.", resource); } else { await res.Start(); } } // start synchronizing the started resources resManager.StartSynchronization(); // main loop int lastTickCount = Environment.TickCount; while (true) { Thread.Sleep(5); var tc = Environment.TickCount; gameServer.Tick(tc - lastTickCount); lastTickCount = tc; } }
private async Task Start(string configFileName) { Configuration config; try { config = Configuration.Load(configFileName ?? "citmp-server.yml"); // if running on WinNT default to using windowed logger if (Environment.OSVersion.Platform == PlatformID.Win32NT && !config.DisableWindowedLogger) { WindowedLogger.Initialize(config.DebugLog); } if (config.AutoStartResources == null) { this.Log().Fatal("No auto-started resources were configured."); return; } if (config.ListenPort == 0) { this.Log().Fatal("No port was configured."); return; } if (config.Downloads == null) { config.Downloads = new Dictionary<string, DownloadConfiguration>(); } } catch (System.IO.IOException) { this.Log().Fatal("Could not open the configuration file {0}.", configFileName ?? "citmp-server.yml"); return; } var platformServer = config.PlatformServer ?? "iv-platform.prod.citizen.re"; var client = new NPClient(platformServer, (config.PlatformPort == 0) ? (ushort)3036 : (ushort)config.PlatformPort); this.Log().Info("Connecting to Terminal platform server at {0}.", platformServer); var connectResult = client.Connect(); if (!connectResult) { this.Log().Fatal("Could not connect to the configured platform server ({0}).", platformServer); return; } this.Log().Info("Authenticating to Terminal with anonymous license key."); // authenticate anonymously var task = client.AuthenticateWithLicenseKey(""); if (!task.Wait(15000)) { this.Log().Fatal("Could not authenticate anonymously to the configured platform server ({0}) - operation timed out.", platformServer); return; } if (!task.Result) { this.Log().Fatal("Could not authenticate anonymously to the configured platform server ({0}).", platformServer); return; } this.Log().Info("Creating initial server instance."); var commandManager = new Commands.CommandManager(); var resManager = new Resources.ResourceManager(config); // create the game server (as resource scanning needs it now) var gameServer = new Game.GameServer(config, resManager, commandManager, client); // preparse resources if (config.PreParseResources != null) { this.Log().Info("Pre-parsing resources: {0}", string.Join(", ", config.PreParseResources)); foreach (var resource in config.PreParseResources) { resManager.ScanResources("resources/", resource); var res = resManager.GetResource(resource); if (res != null) { await res.Start(); } } } else { this.Log().Warn("No PreParseResources defined. This usually means you're using an outdated configuration file. Please consider this."); } // scan resources resManager.ScanResources("resources/"); // start the game server gameServer.Start(); // and initialize the HTTP server var httpServer = new HTTP.HttpServer(config, resManager); httpServer.Start(); // start resources foreach (var resource in config.AutoStartResources) { var res = resManager.GetResource(resource); if (res == null) { this.Log().Error("Could not find auto-started resource {0}.", resource); } else { await res.Start(); } } // start synchronizing the started resources resManager.StartSynchronization(); // main loop int lastTickCount = Environment.TickCount; while (true) { Thread.Sleep(5); var tc = Environment.TickCount; gameServer.Tick(tc - lastTickCount); lastTickCount = tc; } }
private static void Main(string[] args) { // log4net setup SetupLog4Net(); var log = LogManager.GetLogger("Main"); // Arguments if (args.Length < 4) { log.ErrorFormat("Needs 4 arguments: nphostname npport username password [httpport]"); return; } var hostname = args[0]; var port = ushort.Parse(args[1]); var username = args[2]; var password = args[3]; var hport = args.Length > 4 ? ushort.Parse(args[4]) : 5680; // Get session token var ah = new SessionAuthenticationClient(hostname); try { ah.Authenticate(username, password); log.Info("NP authentication successful."); } catch (Exception err) { #if DEBUG log.ErrorFormat("Could not authenticate: {0}", err); #else log.ErrorFormat("Could not authenticate: {0}", err.Message); #endif return; } // NP connection setup log.DebugFormat("Connecting to {0}:{1}...", hostname, port); var np = new NPClient(hostname, port); if (!np.Connect()) { log.Error("Connection to NP server failed."); return; } log.Info("NP connection successful, authenticating..."); // ??? if (!np.AuthenticateWithToken(ah.SessionToken).Result) { np.Disconnect(); log.Error("Authentication to NP server failed."); return; } // HTTP server using (var httpServer = new HttpServer(new HttpRequestProvider())) { log.Info("Starting up HTTP server..."); httpServer.Use(new TcpListenerAdapter(new TcpListener(IPAddress.Any, hport))); httpServer.Use(new HttpRouter() .With("user", new NP2HTTPUserFileHandler(np)) .With("pub", new NP2HTTPPublisherFileHandler(np)) ); httpServer.Use(new AnonymousHttpRequestHandler((context, next) => { context.Response = new HttpResponse(HttpResponseCode.NotFound, "File not found", context.Request.Headers.KeepAliveConnection()); return(Task.Factory.GetCompleted()); })); httpServer.Start(); log.InfoFormat("HTTP server now running on port {0}.", hport); log.InfoFormat("Access publisher files through http://{0}:{1}/pub/<file>", IPAddress.Any, hport); log.InfoFormat("Access user files through http://{0}:{1}/user/<file>", IPAddress.Any, hport); log.Info("You can shut down the HTTP server by pressing any key."); Console.ReadKey(); } }