static void Main(string[] args) { var localhost = "http://127.0.0.1"; var port = Console.ReadLine(); var server = new Server(localhost, port); server.Start(); }
/// <summary> /// Initialise a HTTP server /// </summary> /// <param name="path">The path to the web root of the http server</param> public WebServer(string path) { _httpServer = new HttpServer.Server(); // Add the controller module and all controllers var controllerModule = new RestControllerModule(); var cType = typeof(RestRequestController); AppDomain.CurrentDomain.GetAssemblies().ToList() .SelectMany(s => s.GetTypes()) .Where(p => p.IsSubclassOf(cType) && p != cType && !p.IsAbstract) .ToList() .ForEach(t => controllerModule.Add((RestRequestController)Activator.CreateInstance(t))); _httpServer.Add(controllerModule); // Add the basic file module int cacheDuration = 2592000; Program.Config.TryGetInt("cacheDuration", out cacheDuration); var fileModule = new CachedFileModule(Math.Max(0, cacheDuration)); fileModule.Resources.Add(new HttpServer.Resources.FileResources("/", path)); _httpServer.Add(fileModule); // Set name string serverName; Program.Config.TryGetString("name", out serverName, "Touchee"); _httpServer.ServerName = serverName; // Go to root _httpServer.Add(new SimpleRouter("/", "/index.html")); }
/// <summary> /// Initializes a new instance of the <see cref="Server"/> class. /// </summary> /// <param name="factory">Factory used to create objects used in this library.</param> public Server(HttpFactory factory) { ServerName = "C# WebServer"; _server = this; _factory = factory; AuthenticationProvider = new AuthenticationProvider(); }
private static void Main(string[] args) { var filter = new LogFilter(); filter.AddStandardRules(); //LogFactory.Assign(new ConsoleLogFactory(filter)); // create a server. var server = new Server(); // same as previous example. var module = new FileModule(); module.Resources.Add(new FileResources("/", Environment.CurrentDirectory + "\\files\\")); server.Add(module); server.RequestReceived += OnRequest; server.Add(new MultiPartDecoder()); // use one http listener. server.Add(HttpListener.Create(IPAddress.Any, 8085)); server.Add(new SimpleRouter("/", "/index.html")); // start server, can have max 5 pending accepts. server.Start(5); Console.ReadLine(); }
//Control public static void Init() { //See if there is a new version of the web files waiting before we start the server if (File.Exists(Core.RootFolder + @"\web.zip")) { if (Directory.Exists(Core.RootFolder + @"\web\")) Directory.Delete(Core.RootFolder + @"\web\", true); Directory.CreateDirectory(YAMS.Core.RootFolder + @"\web\"); AutoUpdate.ExtractZip(YAMS.Core.RootFolder + @"\web.zip", YAMS.Core.RootFolder + @"\web\"); File.Delete(Core.RootFolder + @"\web.zip"); } adminServer = new Server(); publicServer = new Server(); //Handle the requests for static files var adminModule = new FileModule(); adminModule.Resources.Add(new FileResources("/assets/", YAMS.Core.RootFolder + "\\web\\assets\\")); adminServer.Add(adminModule); //Add any server specific folders var publicModule = new FileModule(); publicModule.Resources.Add(new FileResources("/assets/", YAMS.Core.RootFolder + "\\web\\assets\\")); SqlCeDataReader readerServers = YAMS.Database.GetServers(); while (readerServers.Read()) { var intServerID = readerServers["ServerID"].ToString(); if (!Directory.Exists(Core.StoragePath + intServerID + "\\renders\\")) Directory.CreateDirectory(Core.StoragePath + intServerID + "\\renders\\"); publicModule.Resources.Add(new FileResources("/servers/" + intServerID + "/renders/", Core.StoragePath + intServerID + "\\renders\\")); if (!Directory.Exists(Core.StoragePath + intServerID + "\\backups\\")) Directory.CreateDirectory(Core.StoragePath + intServerID + "\\backups\\"); publicModule.Resources.Add(new FileResources("/servers/" + intServerID + "/backups/", Core.StoragePath + intServerID + "\\backups\\")); } publicServer.Add(publicModule); //Handle requests to API adminServer.Add(new Web.AdminAPI()); publicServer.Add(new Web.PublicAPI()); adminServer.Add(HttpListener.Create(IPAddress.Any, Convert.ToInt32(YAMS.Database.GetSetting("AdminListenPort", "YAMS")))); publicServer.Add(HttpListener.Create(IPAddress.Any, Convert.ToInt32(YAMS.Database.GetSetting("PublicListenPort", "YAMS")))); adminServer.ErrorPageRequested += new EventHandler<ErrorPageEventArgs>(myServer_ErrorPageRequested); publicServer.ErrorPageRequested += new EventHandler<ErrorPageEventArgs>(myServer_ErrorPageRequested); adminServerThread = new Thread(new ThreadStart(StartAdmin)); publicServerThread = new Thread(new ThreadStart(StartPublic)); adminServerThread.Start(); publicServerThread.Start(); //Open firewall ports Networking.OpenFirewallPort(Convert.ToInt32(YAMS.Database.GetSetting("AdminListenPort", "YAMS")), "Admin website"); Networking.OpenFirewallPort(Convert.ToInt32(YAMS.Database.GetSetting("PublicListenPort", "YAMS")), "Public website"); Networking.OpenUPnP(Convert.ToInt32(YAMS.Database.GetSetting("AdminListenPort", "YAMS")), "Admin website"); Networking.OpenUPnP(Convert.ToInt32(YAMS.Database.GetSetting("PublicListenPort", "YAMS")), "Public website"); }
public MCAdminSession(Server server, bool autoCreate, Type type) { if (_sessionProvider == null) { _sessionProvider = new MCAdminSessionProvider(server, autoCreate, type); } else if (_sessionProvider.Server != server) { throw new InvalidOperationException("Server differs from that of the Session Provider."); } Server = server; _sessId = Guid.NewGuid(); }
public static void HttpRestServer() { var server = new Server(); var module = new RestModule(); module.Endpoints.Add(new ReceiveRestEndpoint()); module.Endpoints.Add(new SyncRestEndpoint()); module.Endpoints.Add(new StopRestEndpoint()); server.Add(module); // use one http listener. server.Add(HttpServer.HttpListener.Create(IPAddress.Loopback, DebugKeys.HttpListenerPort)); server.Start(5); }
public static void Start() { if (_webServer != null) { _webServer.Start(0); return; } _webServer = new Server(); _webServer.Add(HttpListener.Create(IPAddress.Any, 8080)); _webServer.PrepareRequest += OnRequest; _webServer.Add(new StaticResourceHandler()); _webServer.Add(new PageHandler()); _webServer.Add(new SimpleRouter("/", "index.htm")); UserSession.Init(_webServer, true); _webServer.Start(0); }
//public WebServer(IPAddress address) //{ // _ipAddress = address; // // same as previous example. // Setup(); //} public void Setup() { try { _server = new HttpServer.Server(); var module = new FileModule(); module.Resources.Add(new FileResources("/", ScoreboardConfig.SAVE_SERVER_FILES_FOLDER)); _server.Add(module); _server.RequestReceived += OnRequest; _server.Add(new MultiPartDecoder()); // use one http listener. _server.Add(new SimpleRouter("/", "/index.html")); _server.Add(new JsonRouter("/GrabOverlayUpdate")); _server.Add(new JsonRouter("/GrabMobileUpdate")); _server.Add(new JsonRouter("/GetTeam1Members")); _server.Add(new JsonRouter("/GetTeam2Members")); _server.Add(new JsonRouter("/getJamNumber")); _server.Add(new JsonRouter("/addAssist")); _server.Add(new JsonRouter("/removeAssist")); _server.Add(new JsonRouter("/addBlock")); _server.Add(new JsonRouter("/removeBlock")); _server.Add(new JsonRouter("/scoringLoaded")); _server.Add(new JsonRouter("/addScore")); _server.Add(new JsonRouter("/removeScore")); _server.Add(new JsonRouter("/setBlocker1")); _server.Add(new JsonRouter("/setBlocker2")); _server.Add(new JsonRouter("/setBlocker3")); _server.Add(new JsonRouter("/setBlocker4")); _server.Add(new JsonRouter("/setPivot")); _server.Add(new JsonRouter("/setJammer")); _server.Add(new JsonRouter("/setPBox")); _server.Add(new JsonRouter("/addpenalty")); _server.Add(new JsonRouter("/getallpenaltytypes")); _server.Add(new JsonRouter("/loadMainScreen")); PortNumber = portsToTry[triedIndex]; _server.Add(HttpListener.Create(IpAddress, PortNumber)); } catch (Exception exception) { ErrorViewModel.Save(exception, GetType()); } }
private static void StartHTTP() { try { HttpServer.Logging.LogFactory.Assign(new HttpServer.Logging.ConsoleLogFactory(new HttpServer.Logging.LogFilter())); HTTP = new Server(); HTTP.Add(HttpListener.Create(System.Net.IPAddress.Any, Settings.Get("HttpPort", 7780))); HTTP.Add(new HttpMod()); HTTP.Start(32); LocalFileStorage = Settings.Get("LocalFiles", new Dictionary <string, string>()); } catch (Exception ex) { Trace.WriteLine("HTTP Startup Error: " + ex.Message); } }
public MCAdminSessionProvider(Server server, bool autoCreate, Type sessionType) { while (sessionType.BaseType != typeof(MCAdminSession)) { if (sessionType.BaseType == typeof(object)) //Avoid infinite loops. { throw new InvalidOperationException("Argument \"sessionType\" must contain the base type MCAdmin.WebAccess.Sessions.MCAdminSession."); } } _server = server; _sessions = new List<MCAdminSession>(); _autoCreate = autoCreate; _sessionType = sessionType; server.PrepareRequest += OnRequest; }
//Control public static void Init() { adminServer = new Server(); //Handle the requests for static files var adminModule = new FileModule(); adminModule.Resources.Add(new FileResources("/assets/", YAMS.Core.RootFolder + "\\web\\assets\\")); adminServer.Add(adminModule); //Handle requests to API adminServer.Add(new Web.AdminAPI()); adminServer.Add(HttpListener.Create(IPAddress.Any, Convert.ToInt32(YAMS.Database.GetSetting("AdminListenPort", "YAMS")))); adminServer.ErrorPageRequested += new EventHandler<ErrorPageEventArgs>(myServer_ErrorPageRequested); adminServerThread = new Thread(new ThreadStart(StartAdmin)); adminServerThread.Start(); //Open firewall ports if (Database.GetSetting("EnableOpenFirewall", "YAMS") == "true") { Networking.OpenFirewallPort(Convert.ToInt32(YAMS.Database.GetSetting("AdminListenPort", "YAMS")), "Admin website"); } }
static void Main(string[] args) { string port = "65000"; foreach (string arg in args) if (arg.ToLower().StartsWith("port=")) port = arg.Split("=".ToCharArray())[1]; var addresses = new List<string>() { "http://" + GetIP().ToString() + ":" + port + "/", "http://localhost:" + port + "/", "http://127.0.0.1:" + port + "/" }; Console.WriteLine("Host Name: " + Dns.GetHostName()); addresses.ForEach(a => Console.WriteLine(a)); server = new Server(addresses); RegisterControllers(); server.Listen(); }
static void Main(string[] args) { // create a server. var server = new Server(); // same as previous example. var module = new FileModule(); module.Resources.Add(new FileResources("/", Environment.CurrentDirectory + "\\files\\")); server.Add(module); // use one http listener. server.Add(HttpListener.Create(IPAddress.Any, 8085)); // add our own module. server.Add(new Streamer()); // start server, can have max 5 pending accepts. server.Start(5); Console.ReadLine(); }
public WordLaunch(ServerInfo targetserver) { InitializeComponent(); this.targetserver = targetserver; plugin = new PluginRpc(targetserver.conn.URL); medsize = plugin.GetMediumSize(); txt_Content.NativeInterface.SetCodePage((int)Constants.SC_CP_UTF8); CategoryFullInfo[] cfi = targetserver.conn.GetCategories(0, targetserver.username, targetserver.password); foreach (CategoryFullInfo cf in cfi) { CheckBox cb = new CheckBox(); cb.Name = "cb_" + cf.categoryName; cb.Text = cf.categoryName; cb.Tag = cf; flow_Categories.Controls.Add(cb); } postResources = GetNextAvailableDir(); Directory.CreateDirectory(postResources); var module = new FileModule(); webserv = new Server(); module.Resources.Add(new FileResources("/",postResources)); webserv.Add(module); webserv.Add(new MultiPartDecoder()); webserv.RequestReceived+=new EventHandler<RequestEventArgs>(webserv_RequestReceived); // use one http listener. webserv.Add(HttpListener.Create(System.Net.IPAddress.Any, webservport)); webserv.Start(5); // Find a valid post to use url = targetserver.conn.URL.Replace("xmlrpc.php", "?p=2147483646"); }
public override void Init(Kernel kernel) { PluginOptions = new PluginConfiguration<PluginOptions>(kernel, this.GetType().Assembly); PluginOptions.Load(); Logger.ReportInfo("MBWeb (version "+Version+") Plug-in loaded."); server = new Server(); server.Add(HttpServer.HttpListener.Create(IPAddress.Any, 9999)); var module = new TinyWebModule(); module.MapPath("/", "/index.html"); server.Add(module); server.Start(5); }
private void OnRequest(object sender, RequestEventArgs e) { _server = this; Exception exception; try { ProcessingResult result = HandleRequest(e); if (result != ProcessingResult.Continue) return; exception = null; } catch (HttpException err) { _logger.Error("Got an HTTP exception.", err); e.Response.Status = err.Code; e.Response.Reason = err.Message; exception = err; } catch (Exception err) { _logger.Error("Got an unhandled exception.", err); exception = err; e.Response.Status = HttpStatusCode.InternalServerError; e.Response.Reason = "Failed to process request."; } if (exception == null) { e.Response.Status = HttpStatusCode.NotFound; e.Response.Reason = "Requested resource is not found. Sorry ;("; exception = new HttpException(HttpStatusCode.NotFound, "Failed to find uri " + e.Request.Uri); } DisplayErrorPage(e.Context, exception); e.IsHandled = true; }
private void Listener_OnErrorPage(object sender, ErrorPageEventArgs e) { _server = this; DisplayErrorPage(e.Context, e.Exception); e.IsHandled = true; }
/// <summary> /// Initializes a new instance of the <see cref="Server"/> class. /// </summary> public Server() { _server = this; _factory = new HttpFactory(); }
public NancyHost(IPAddress address, int port, INancyBootstrapper bootStrapper) { var filter = new LogFilter(); filter.AddStandardRules(); LogFactory.Assign(new ConsoleLogFactory(filter)); server = new Server(); bootStrapper.Initialise(); engine = bootStrapper.GetEngine(); // same as previous example. AppiaModule module = new AppiaModule(engine); server.Add(module); }
public WebInterface() { if (WebInterfaceEnabled) { this.server = new Server(); this.interpreter = new ManagedFileModule(); this.server.Add(this.interpreter); this.reader = new FileModule(); this.resource = new FileResources("/", Path.Combine(Directory.GetCurrentDirectory(), "WebInterface")); this.reader.Resources.Add(resource); this.server.Add(this.reader); this.server.Add(new SimpleRouter("/", "/index.html")); if (WebInterfaceDebug) { if (UseSSL) { // } else { // } } if (UseSSL) { try { this.certificate = new X509Certificate2(CertificatePath); } catch (DirectoryNotFoundException) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("({0}) <Web Interface> Error: The directory specified could not be found.", DateTime.Now.ToString("hh:mm")); } catch (IOException) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("({0}) <Web Interface> Error: A file in the directory could not be accessed.", DateTime.Now.ToString("hh:mm")); } catch (NullReferenceException) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("({0}) <Web Interface> File must be a .cer file. Program does not have access to that type of file.", DateTime.Now.ToString("hh:mm")); } Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("({0}) <Web Interface> Loaded Certificate: {1} Valid Date: {2} Expiry Date: {3}", DateTime.Now.ToString("hh:mm"), Path.GetFileName(CertificatePath), this.certificate.NotBefore, this.certificate.NotAfter); this.securelistener = (SecureHttpListener) HttpListener.Create(IPAddress.Parse(ListenAddress), Port, this.certificate); this.securelistener.UseClientCertificate = true; this.server.Add(this.securelistener); } else { this.listener = HttpListener.Create(IPAddress.Parse(ListenAddress), Port); this.server.Add(this.listener); } this.reader.ContentTypes.Clear(); this.reader.ContentTypes.Add("default", new ContentTypeHeader("application/octet-stream")); foreach (var mimetype in AllowedMimeTypes) { var sbstr = mimetype.Split(','); switch (sbstr.Length) { case 2: if (sbstr[0].Length != 0 && sbstr[1].Length != 0) { try { this.reader.ContentTypes.Add(sbstr[0], new ContentTypeHeader(sbstr[1])); } catch (ArgumentException) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("({0}) <Web Interface> Config.xml contains duplicate Mime Types.", DateTime.Now.ToString("hh:mm")); } } else { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("({0}) <Web Interface> Config.xml contains invalid Mime Types.", DateTime.Now.ToString("hh:mm")); } break; default: Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("({0}) <Web Interface> Config.xml contains invalid Mime Types.", DateTime.Now.ToString("hh:mm")); break; } } try { this.server.Start(5); SessionManager.Start(this.server); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("({0}) <Web Interface> Running on Port {1}...", DateTime.Now.ToString("hh:mm"), Port); } catch (SocketException e) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("({0}) <Web Interface> {1}", DateTime.Now.ToString("hh:mm"), e); } } else { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("({0}) <Web Interface> Disabled", DateTime.Now.ToString("hh:mm")); } }
internal static void Start(Server webServer) { _sessionProvider.Start(webServer); }
public UserSession(Server server, bool autoCreate) : base(server, autoCreate, typeof(UserSession)) { }
private static void StartWebServer(string uri, string absolutePath, int port) { // create a server. var server = new Server(); // add module to serve files i.e. act like a web server var module = new FileModule(); // Add mime types for Silverlight PivotViewer module.ContentTypes.Add("xaml", new ContentTypeHeader("application/xaml+xml")); module.ContentTypes.Add("xap", new ContentTypeHeader("application/x-silverlight-2")); module.ContentTypes.Add("cxml", new ContentTypeHeader("text/xml")); module.ContentTypes.Add("xml", new ContentTypeHeader("text/xml")); module.ContentTypes.Add("dzi", new ContentTypeHeader("text/xml")); module.ContentTypes.Add("dzc", new ContentTypeHeader("text/xml")); module.Resources.Add(new FileResources("/", absolutePath)); server.Add(module); // use one http listener. server.Add(HttpListener.Create(IPAddress.Any, port)); // start server, can have max 5 pending accepts. server.Start(5); }
static void Main(string[] args) { var server = new Server(); server.Start(); }
public static void Init(Server server, bool autoCreate) { new UserSession(server, autoCreate); }
/// <summary> /// Initializes a new instance of the <see cref="Server"/> class. /// </summary> /// <param name="factory">Factory used to create objects used in this library.</param> public Server(HttpFactory factory) { _server = this; _factory = factory; }
/// <summary> /// Creates a new UserSession. /// </summary> /// <param name="server">The server holding the session</param> /// <param name="userId">The Id of the client</param> /// <param name="username">TEMPOARY: The username of the client</param> /// <returns></returns> public static UserSession Create(Server server, int userId, string username) { //TODO: Get user information from database UserSession session = _sessionProvider.Create(typeof(UserSession)) as UserSession; if (session == null) { throw new Exception("Session is null! Check your code!"); } session.UserId = userId; session.Username = username; return session; }
private void OnErrorPage(object sender, ErrorPageEventArgs e) { _server = this; ErrorPageRequested(this, e); }
private void OnRequest(object sender, RequestEventArgs e) { _server = this; Exception exception; try { if (HandleRequest(e) != ProcessingResult.Continue) return; exception = null; } catch (HttpException err) { _logger.Error("Got an HTTP exception.", err); e.Response.Status = err.Code; e.Response.Reason = err.Message; exception = err; } catch (Exception err) { _logger.Error("Got an exception.", err); var args = new ExceptionEventArgs(err); TriggerExceptionThrown(args); exception = err; e.Response.Status = HttpStatusCode.InternalServerError; e.Response.Reason = "Failed to process request."; } if (exception == null) { e.Response.Status = HttpStatusCode.NotFound; e.Response.Reason = "Requested resource is not found. Sorry ;("; } SendErrorPage(e, exception); }
public Processor(TcpClient client, Server httpServer) { Socket = client; Server = httpServer; }