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(); }
public EventQueueServer(HttpListener server) { this.server = server; eventQueue = new BlockingQueue <EventQueueEvent>(); running = true; currentID = 1; }
public EventQueueServer(HttpListener server) { this.server = server; eventQueue = new BlockingQueue<EventQueueEvent>(); running = true; currentID = 1; }
public void Start(String localIp, int port) { Port = port; _listener = HttpServer.HttpListener.Create(System.Net.IPAddress.Any, port); _listener.RequestReceived += new EventHandler <RequestEventArgs>(_listener_RequestReceived); _listener.Start(MaxThreads); }
public void Start() { //HttpServer.Logging.LogFactory.Assign(new HttpServer.Logging.ConsoleLogFactory(null)); // TODO: more than one Interception can be configured with the same port and IP foreach (var interception in state_.Config.Interceptions) { IPAddress ip = GetIp(interception.IPv4); if (ip == null) { state_.Logger.Error("Invalid IPv4 address: {0}", interception.IPv4); continue; } state_.Logger.Information("Intercept {0} {2} {3}:{1}", interception.Protocol, interception.Port, interception.Name, ip); try { HttpListener listener = interception.Protocol == Protocol.Https ? HttpListener.Create(ip, interception.Port, certificatesMgr_.GetCertificate(interception.Name)) : HttpListener.Create(ip, interception.Port); listener.RequestReceived += OnRequest; listener.Start(state_.Config.Web.WebBacklog); listeners_.Add(listener); } catch (System.Net.Sockets.SocketException e) { state_.Logger.Exception(e, "Error setting up listener on port {0}", interception.Port); } } }
/// <summary> /// Closes this control point. This will first disconnect all connected devices and then release all lower-level UPnP /// protocol layers. /// The network tracker must be closed before this method is called. /// </summary> public void Close() { ICollection <HttpListener> listenersToClose = new List <HttpListener>(); lock (_cpData.SyncObj) { if (!_isActive) { return; } _isActive = false; if (_httpListenerV4 != null) { listenersToClose.Add(_httpListenerV4); _httpListenerV4 = null; } _httpListenerV4 = null; if (_httpListenerV6 != null) { listenersToClose.Add(_httpListenerV6); _httpListenerV6 = null; } _networkTracker.RootDeviceRemoved -= OnRootDeviceRemoved; _networkTracker.DeviceRebooted -= OnDeviceRebooted; } // Outside the lock DisconnectAll(); foreach (HttpListener httpListener in listenersToClose) { httpListener.Stop(); } }
private static void Main(string[] args) { HttpListener listener = HttpListener.Create(IPAddress.Any, 8089); listener.RequestReceived += OnRequest; listener.Start(5); Thread.Sleep(9000000); }
private static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Console.Title = "Web Server"; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(" Rains Soft Web Server"); Console.WriteLine(" Rains Soft"); Console.WriteLine(" http://www.mobanhou.com"); Console.WriteLine(); Console.ResetColor(); int i = 0; while (true) { if (i > 9) { Console.WriteLine("."); break; } else { Console.Write("."); i++; } System.Threading.Thread.Sleep(500); } var filter = new LogFilter(); filter.AddStandardRules(); var log = new ConsoleLogFactory(filter); LogFactory.Assign(log); Logger = LogFactory.CreateLogger(log.GetType()) as ConsoleAndTextLogger; Logger.Info("create server"); // 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.Add(new CustomHttpModule()); server.RequestReceived += OnRequest; server.Add(new MultiPartDecoder()); // use one http listener. server.Add(HttpListener.Create(IPAddress.Any, 8085)); server.Add(new SimpleRouter("/", "/index.html")); Logger.Info("start server"); // start server, can have max 5 pending accepts. server.Start(5); Console.Beep(); Console.ReadLine(); }
/// <summary> /// Starts this UPnP control point. All device templates should be configured at the time this method gets called. /// The network tracker must be started after this method is called, else we might miss some connect events. /// </summary> public void Start() { lock (_cpData.SyncObj) { if (_isActive) { throw new IllegalCallException("UPnP control point mustn't be started multiple times"); } UPnPConfiguration.LOGGER.Debug("Will listen on IPs filtered by [{0}]", (UPnPConfiguration.IP_ADDRESS_BINDINGS != null ? String.Join(",", UPnPConfiguration.IP_ADDRESS_BINDINGS) : null)); _cpData.HttpPortV4 = 0; if (UPnPConfiguration.USE_IPV4) { foreach (IPAddress address in NetworkHelper.GetBindableIPAddresses(AddressFamily.InterNetwork, UPnPConfiguration.IP_ADDRESS_BINDINGS)) { HttpListener httpListenerV4 = HttpListener.Create(address, _cpData.HttpPortV4); httpListenerV4.RequestReceived += OnHttpListenerRequestReceived; try { httpListenerV4.Start(DEFAULT_HTTP_REQUEST_QUEUE_SIZE); // Might fail if IPv4 isn't installed _cpData.HttpPortV4 = httpListenerV4.LocalEndpoint.Port; UPnPConfiguration.LOGGER.Debug("UPnPControlPoint: HTTP listener for IPv4 protocol started at address '{0}' on port '{1}'", address, _cpData.HttpPortV4); _httpListeners.Add(httpListenerV4); } catch (SocketException e) { UPnPConfiguration.LOGGER.Warn("UPnPControlPoint: Error starting HTTP server (IPv4)", e); } } } _cpData.HttpPortV6 = 0; if (UPnPConfiguration.USE_IPV6) { foreach (IPAddress address in NetworkHelper.GetBindableIPAddresses(AddressFamily.InterNetworkV6, UPnPConfiguration.IP_ADDRESS_BINDINGS)) { HttpListener httpListenerV6 = HttpListener.Create(address, _cpData.HttpPortV6); httpListenerV6.RequestReceived += OnHttpListenerRequestReceived; try { httpListenerV6.Start(DEFAULT_HTTP_REQUEST_QUEUE_SIZE); // Might fail if IPv6 isn't installed _cpData.HttpPortV6 = httpListenerV6.LocalEndpoint.Port; UPnPConfiguration.LOGGER.Debug("UPnPControlPoint: HTTP listener for IPv6 protocol started at address '{0}' on port '{1}'", address, _cpData.HttpPortV6); _httpListeners.Add(httpListenerV6); } catch (SocketException e) { UPnPConfiguration.LOGGER.Warn("UPnPControlPoint: Error starting HTTP server (IPv6)", e); } } } _networkTracker.RootDeviceRemoved += OnRootDeviceRemoved; _networkTracker.DeviceRebooted += OnDeviceRebooted; _isActive = true; } }
public static void Open(int Port, int backlog = 5) { if (httpListener == null) { httpListener = HttpServer.HttpListener.Create(IPAddress.Any, Port); httpListener.RequestReceived += HttpListener_RequestReceived; } httpListener.Start(backlog); }
/// <summary> /// Starts this UPnP control point. All device templates should be configured at the time this method gets called. /// The network tracker must be started after this method is called, else we might miss some connect events. /// </summary> public void Start() { lock (_cpData.SyncObj) { if (_isActive) { throw new IllegalCallException("UPnP control point mustn't be started multiple times"); } if (UPnPConfiguration.USE_IPV4) { _httpListenerV4 = HttpListener.Create(IPAddress.Any, 0); _httpListenerV4.RequestReceived += OnHttpListenerRequestReceived; try { _httpListenerV4.Start(DEFAULT_HTTP_REQUEST_QUEUE_SIZE); // Might fail if IPv4 isn't installed _cpData.HttpPortV4 = _httpListenerV4.LocalEndpoint.Port; } catch (SocketException e) { _httpListenerV4 = null; _cpData.HttpPortV4 = 0; UPnPConfiguration.LOGGER.Warn("UPnPControlPoint: Error starting HTTP server (IPv4)", e); } } else { _httpListenerV4 = null; _cpData.HttpPortV4 = 0; } if (UPnPConfiguration.USE_IPV6) { _httpListenerV6 = HttpListener.Create(IPAddress.IPv6Any, 0); _httpListenerV6.RequestReceived += OnHttpListenerRequestReceived; try { _httpListenerV6.Start(DEFAULT_HTTP_REQUEST_QUEUE_SIZE); // Might fail if IPv6 isn't installed _cpData.HttpPortV6 = _httpListenerV6.LocalEndpoint.Port; } catch (SocketException e) { _httpListenerV6 = null; _cpData.HttpPortV6 = 0; UPnPConfiguration.LOGGER.Warn("UPnPControlPoint: Error starting HTTP server (IPv6)", e); } } else { _httpListenerV6 = null; _cpData.HttpPortV6 = 0; } _networkTracker.RootDeviceRemoved += OnRootDeviceRemoved; _networkTracker.DeviceRebooted += OnDeviceRebooted; _isActive = true; } }
public void Start() { // use one http listener. server.Add(HttpListener.Create(IPAddress.Any, 8888)); shouldContinue = true; server.Start(5); }
public virtual void Start() { if (listener == null) { listener = HttpListener.Create(Ip, Port); listener.RequestReceived += OnRequest; listener.Start(int.MaxValue); } }
/// <summary> /// Instantiate an HTTP server. /// </summary> public OSHttpServer(IPAddress address, int port, int poolSize) { _engineId = String.Format("OSHttpServer (HTTP:{0})", port); _isSecure = false; _log.DebugFormat("[{0}] HTTP server instantiated", EngineID); _listener = new HttpListener(address, port); _queue = new OSHttpRequestQueue(); _pumps = OSHttpRequestPump.Pumps(this, _queue, poolSize); }
/// <summary> /// Instantiate an HTTPS server. /// </summary> public OSHttpServer(IPAddress address, int port, X509Certificate certificate, int poolSize) { _engineId = String.Format("OSHttpServer [HTTPS:{0}/ps:{1}]", port, poolSize); _isSecure = true; _log.DebugFormat("[{0}] HTTPS server instantiated", EngineID); _listener = new HttpListener(address, port, certificate); _queue = new OSHttpRequestQueue(); _pumps = OSHttpRequestPump.Pumps(this, _queue, poolSize); }
private void StartListner(HttpServer.HttpListener httpListenner) { m_listener.Start(5); m_eventLogger.WriteError("启动Http监听成功..."); string text = string.Format("时间:" + DateTime.Now.ToString() + "\n" + " 建立HttpServer,启动Http监听成功.."); USeNotifyEventArgs notify = new USeNotifyEventArgs(USeNotifyLevel.Warning, text); SafeRaiseNotifyEvent(this, notify); }
/// <summary> /// Disposes the RESTful API service /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { if (disposing) { if (listener != null) { listener.Stop(); listener = null; } } }
public void StartTutorial() { Console.WriteLine("Welcome to Tutorial #1!"); Console.WriteLine(); Console.WriteLine("HttpListener allows you to handle everything yourself."); Console.WriteLine(); Console.WriteLine("Browse to http://localhost:8081/hello and http://localhost:8081/goodbye to view the contents"); _listener = HttpListener.Create(IPAddress.Any, 8081); _listener.RequestReceived += OnRequest; _listener.Start(5); }
public bool Initialize(IHost hostApplication) { My = hostApplication; if (!System.IO.File.Exists("webserver.cfg")) { WebServer.WebConfig.Add("RootWebDir", "./web/"); WebServer.WebConfig.Add("MaxPostSize", "102400"); WebServer.WebConfig.Add("PathToPHP", "/usr/bin/php"); WebServer.WebConfig.Add("IndexFile", "index.php,index.fritz"); WebServer.WebConfig.Add("Port", "80"); FeuerwehrCloud.Helper.AppSettings.Save(WebServer.WebConfig, "webserver.cfg"); } WebServer.WebConfig = FeuerwehrCloud.Helper.AppSettings.Load("webserver.cfg"); FeuerwehrCloud.Helper.Logger.WriteLine("| *** WebServer loaded: listening on port: " + WebServer.WebConfig["Port"]); WebServer.WSThread = new System.Threading.Thread(delegate() { WebServer.listener = HttpServer.HttpListener.Create(IPAddress.Any, int.Parse(WebServer.WebConfig["Port"])); var server = new Server(); server.MaxContentSize = int.Parse(WebServer.WebConfig["MaxPostSize"]); var deivaModule = new DEIVAModule(hostApplication); server.Add(deivaModule); var cgiService = new CgiService(WebServer.WebConfig["PathToPHP"], "php"); var cgiModule = new CgiModule(WebServer.WebConfig["RootWebDir"], cgiService); server.Add(cgiModule); //var avmModule = new AVMModule(WebServer.WebConfig["RootWebDir"], hostApplication); //server.Add(avmModule); var fileService = new DiskFileService("/", WebServer.WebConfig["RootWebDir"]); var fileModule = new GzipFileModule(fileService) { EnableGzip = true }; server.Add(fileModule); var router = new DefaultIndexRouter(WebServer.WebConfig["RootWebDir"]); router.AddIndexFile(WebServer.WebConfig["IndexFile"]); server.Add(router); var dirModule = new DirectoryModule(fileService); server.Add(dirModule); server.Add(listener); try { server.Start(10); ThreadExitEvent.WaitOne(); server.Stop(true); } catch (System.Exception ex) { if (ex.Message.Contains("already in")) { FeuerwehrCloud.Helper.Logger.WriteLine("Kann FeuerwehrCloud-Server HTTP-Modul nicht starten!"); } } }); WebServer.WSThread.Start(); return(true); }
private static void Main(string[] args) { var certificate = new X509Certificate2("C:\\OpenSSL\\bin\\newcert.p12", "test"); // We do the cast since we want to specify UseClientCert var listener = (SecureHttpListener)HttpListener.Create(IPAddress.Any, 8080, certificate); listener.UseClientCertificate = true; listener.RequestReceived += OnRequest; listener.Start(5); Console.ReadLine(); }
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 virtual void Start() { try { listener = HttpListener.Create(Ip, Port); listener.RequestReceived += OnRequest; listener.Start(int.MaxValue); } catch (Exception ex) { TShock.Log.Error("Fatal Startup Exception"); TShock.Log.Error(ex.ToString()); TShock.Log.ConsoleError("Invalid REST configuration: \nYou may already have a REST service bound to port {0}. \nPlease adjust your configuration and restart the server. \nPress any key to exit.", Port); Console.ReadLine(); Environment.Exit(1); } }
internal void Init() { #if USE_HTTPSERVER_DLL _listener = HttpServer.HttpListener.Create(new CHLogger(this), IPAddress.Any, _port); _listener.Accepted += _listener_Accepted; _listener.Set404Handler(_listener_404); #endif HttpServerUtil.workArroundReuse(_port); try { _listener.Start(10); LogInfo("Ready for HTTPD port " + _port); new SystemHttpServer(clientManager, _port + 10, "first_robot_name"); WriteLine("Ready for HTTPD port " + _port); } catch (Exception e) { WriteLine("NOT OK for HTTPD port " + _port + "\n" + e); } }
private void btnDesbLocal_Click(object sender, EventArgs e) { btnDesbLocal.Enabled = false; btnDesbRemoto.Enabled = false; var certificate = new X509Certificate2("cert.p12", "acs.gvt.com.br"); var listener = (SecureHttpListener)HttpListener.Create(IPAddress.Any, 443, certificate); unlockSent = 0; listener.UseClientCertificate = true; listener.RequestReceived += OnRequestDesbloqueio; listener.Start(5); AppendTextBox("Desbloqueio local. Servidor web iniciado.\r\n"); if (configToken.Length == 6) { checkBox1.Enabled = false; AppendTextBox("Apontando host acs.gvt.com.br para " + ipGerencia + "\r\n"); webBrowser1.Navigate("http://" + ipModem + "/cgi-bin/generic.cgi?token=" + configToken + "&write=LANDevice_1_HostConfig_StaticHost_1_IPAddress:" + ipGerencia + "&write=LANDevice_1_HostConfig_StaticHost_1_Hostname:acs.gvt.com.br"); } }
/// <summary> /// Starts the RESTful API service /// </summary> public virtual void Start() { try { listener = HttpListener.Create(Ip, Port); listener.RequestReceived += OnRequest; listener.Start(Int32.MaxValue); tokenBucketTimer = new Timer((e) => { DegradeBucket(); }, null, TimeSpan.Zero, TimeSpan.FromMinutes(Math.Max(Restful.Instance.Config.RequestBucketDecreaseIntervalMinutes, 1))); } catch (Exception ex) { TShock.Log.Error("Fatal Startup Exception"); TShock.Log.Error(ex.ToString()); TShock.Log.ConsoleError("Invalid REST configuration: \nYou may already have a REST service bound to port {0}. \nPlease adjust your configuration and restart the server. \nPress any key to exit.", Port); Console.ReadLine(); Environment.Exit(1); } }
/// <summary> /// Starts the RESTful API service /// </summary> public virtual void Start() { try { listener = HttpListener.Create(Ip, Port); listener.RequestReceived += OnRequest; listener.Start(int.MaxValue); tokenBucketTimer = new Timer((e) => { DegradeBucket(); }, null, TimeSpan.Zero, TimeSpan.FromMinutes(Math.Max(TShock.Config.RESTRequestBucketDecreaseIntervalMinutes, 1))); } catch (Exception ex) { TShock.Log.Error("致命的启动错误."); TShock.Log.Error(ex.ToString()); TShock.Log.ConsoleError("REST配置无效: \n可能端口{0}被已经启动另外的REST占用. \n请调整REST配置并重启服务器. \n任意键退出.", Port); Console.ReadLine(); Environment.Exit(1); } }
//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) { // 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 void StartTutorial() { if (!File.Exists("../../certInProjectFolder.p12")) { Console.WriteLine("Create a certificate first. "); Console.WriteLine("OpenSSL: http://www.openssl.org/"); Console.WriteLine("Create a certificate: http://www.towersoft.com/sdk/doku.php?id=ice:setting_up_an_ice_server_to_use_ssl"); Console.WriteLine(); Console.WriteLine("Create the cert and place it in the tutorial project folder with the name 'certInProjectFolder.p12'."); return; } Console.WriteLine("Welcome to tutorial number 2, which will demonstrate how to setup HttpListener for secure requests."); Console.WriteLine(); Console.WriteLine("You will need to create a certificate yourself. A good guide for OpenSSL can be found here:"); Console.WriteLine("http://www.towersoft.com/sdk/doku.php?id=ice:setting_up_an_ice_server_to_use_ssl"); Console.WriteLine(); Console.WriteLine("Browse to https://localhost/hello when you have installed your certificate."); _cert = new X509Certificate2("../../certInProjectFolder.p12", "yourCertPassword"); _listener = HttpListener.Create(IPAddress.Any, 443, _cert); _listener.RequestReceived+= OnSecureRequest; _listener.Start(5); }
public void StartTutorial() { if (!File.Exists("../../certInProjectFolder.p12")) { Console.WriteLine("Create a certificate first. "); Console.WriteLine("OpenSSL: http://www.openssl.org/"); Console.WriteLine("Create a certificate: http://www.towersoft.com/sdk/doku.php?id=ice:setting_up_an_ice_server_to_use_ssl"); Console.WriteLine(); Console.WriteLine("Create the cert and place it in the tutorial project folder with the name 'certInProjectFolder.p12'."); return; } Console.WriteLine("Welcome to tutorial number 2, which will demonstrate how to setup HttpListener for secure requests."); Console.WriteLine(); Console.WriteLine("You will need to create a certificate yourself. A good guide for OpenSSL can be found here:"); Console.WriteLine("http://www.towersoft.com/sdk/doku.php?id=ice:setting_up_an_ice_server_to_use_ssl"); Console.WriteLine(); Console.WriteLine("Browse to https://localhost/hello when you have installed your certificate."); _cert = new X509Certificate2("../../certInProjectFolder.p12", "yourCertPassword"); _listener = HttpListener.Create(IPAddress.Any, 443, _cert); _listener.RequestReceived += OnSecureRequest; _listener.Start(5); }
public void Start() { LoadRepositories(); HttpRequest.StreamFactory = HttpRequestStreamFactory; // TODO: Specify our address HttpServer.HttpListener listener = HttpServer.HttpListener.Create( IPAddress.Any, PortNumber); listener.RequestReceived += OnRequest; listener.Start(5); int milliSeconds = 1000 * Settings.ManifestFlushIntervalSeconds; System.Threading.TimerCallback cb = new System.Threading.TimerCallback( FlushManifestsCallback); System.Threading.Timer flushTimer = new System.Threading.Timer( cb, null, milliSeconds, milliSeconds); // TODO: Wait for signal System.Threading.Thread.Sleep( System.Threading.Timeout.Infinite); flushTimer.Dispose(); }
private void StartHTTP() { if (HTTPRunning) { return; } int m_port_original = 0; int m_optional_port = 0; try { m_port_original = (int)m_port; m_optional_port = m_port_original + 1; m_HttpListener = CoolHTTPListener.Create(IPAddress.Any, (int)m_port); m_HttpListener.ExceptionThrown += httpServerException; m_HttpListener.RequestReceived += OnRequest; m_HttpListener.Start(m_BotConfig.httpserver.BacklogQueue); HTTPRunning = true; } catch (Exception e) { m_Output.LogMessage("error", "[HTTPD]: Failed to start HTTPD with " + e.Message + ". Trying alternate port." + Environment.NewLine); try { m_HttpListener = CoolHTTPListener.Create(IPAddress.Any, (int)m_optional_port); m_HttpListener.ExceptionThrown += httpServerException; m_HttpListener.RequestReceived += OnRequest; m_HttpListener.Start(m_BotConfig.httpserver.BacklogQueue); HTTPRunning = true; } catch (Exception f) { m_Output.LogMessage("error", "[HTTPD]: Failed to start HTTPD with " + f.Message + Environment.NewLine); } } }
private void StartHTTP() { try { m_log.Info("[HTTPD]: Spawned main thread OK"); //m_httpListener = new HttpListener(); NotSocketErrors = 0; if (!m_ssl) { //m_httpListener.Prefixes.Add("http://+:" + m_port + "/"); //m_httpListener.Prefixes.Add("http://10.1.1.5:" + m_port + "/"); m_httpListener2 = new CoolHTTPListener(m_listenIPAddress, (int)m_port); m_httpListener2.ExceptionThrown += httpServerException; m_httpListener2.LogWriter = httpserverlog; // Uncomment this line in addition to those in HttpServerLogWriter // if you want more detailed trace information from the HttpServer //m_httpListener2.UseTraceLogs = true; m_httpListener2.DisconnectHandler = httpServerDisconnectMonitor; } else { //m_httpListener.Prefixes.Add("https://+:" + (m_sslport) + "/"); //m_httpListener.Prefixes.Add("http://+:" + m_port + "/"); System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2("SineWaveCert.pfx", "123"); m_httpListener2 = new CoolHTTPListener(IPAddress.Any, (int)m_port, cert); m_httpListener2.ExceptionThrown += httpServerException; m_httpListener2.LogWriter = httpserverlog; m_httpListener2.DisconnectHandler = httpServerDisconnectMonitor; } m_httpListener2.RequestHandler += OnHandleRequestIOThread; //m_httpListener.Start(); m_httpListener2.Start(64); HTTPDRunning = true; //HttpListenerContext context; //while (true) //{ // context = m_httpListener.GetContext(); // ThreadPool.QueueUserWorkItem(new WaitCallback(HandleRequest), context); // } } catch (Exception e) { m_log.Error("[HTTPD]: Error - " + e.Message); m_log.Error("[HTTPD]: Tip: Do you have permission to listen on port " + m_port + ", " + m_sslport + "?"); // We want this exception to halt the entire server since in current configurations we aren't too // useful without inbound HTTP. throw e; } }
/// <summary> /// Closes this control point. This will first disconnect all connected devices and then release all lower-level UPnP /// protocol layers. /// The network tracker must be closed before this method is called. /// </summary> public void Close() { ICollection<HttpListener> listenersToClose = new List<HttpListener>(); lock (_cpData.SyncObj) { if (!_isActive) return; _isActive = false; if (_httpListenerV4 != null) { listenersToClose.Add(_httpListenerV4); _httpListenerV4 = null; } _httpListenerV4 = null; if (_httpListenerV6 != null) { listenersToClose.Add(_httpListenerV6); _httpListenerV6 = null; } _networkTracker.RootDeviceRemoved -= OnRootDeviceRemoved; _networkTracker.DeviceRebooted -= OnDeviceRebooted; } // Outside the lock DisconnectAll(); foreach (HttpListener httpListener in listenersToClose) httpListener.Stop(); }
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")); } }
public bool Start(Simian simian) { int port = DEFAULT_HTTP_PORT; string hostname = null; string sslCertFile = null; IPHostEntry entry; IPAddress address; // Create a logger for the HTTP server HttpLogWriter httpLogger = new HttpLogWriter(m_log); // Create a default 404 handler m_notFoundHandler = new HttpRequestHandler(null, Default404Handler, true); #region Config Variables IConfig config = simian.Config.Configs["HTTP"]; if (config != null) { port = config.GetInt("ListenPort", DEFAULT_HTTP_PORT); hostname = config.GetString("Hostname", null); sslCertFile = config.GetString("SSLCertFile", null); } if (String.IsNullOrEmpty(hostname)) { hostname = Dns.GetHostName(); entry = Dns.GetHostEntry(hostname); address = IPAddress.Any; } else { entry = Dns.GetHostEntry(hostname); if (entry != null && entry.AddressList.Length > 0) { address = entry.AddressList[0]; } else { m_log.Warn("Could not resolve an IP address from hostname " + hostname + ", binding to all interfaces"); address = IPAddress.Any; } } #endregion Config Variables #region Initialization if (!String.IsNullOrEmpty(sslCertFile)) { // HTTPS mode try { m_sslCertificate = new X509Certificate2(sslCertFile); } catch (Exception ex) { m_log.Error("Failed to load SSL certificate file \"" + sslCertFile + "\": " + ex.Message); return false; } m_uri = new Uri("https://" + hostname + (port != 80 ? (":" + port) : String.Empty)); m_httpServer = HttpServer.HttpListener.Create(address, port, m_sslCertificate, RemoteCertificateValidationHandler, SslProtocols.Default, false); } else { // HTTP mode m_uri = new Uri("http://" + hostname + (port != 80 ? (":" + port) : String.Empty)); m_httpServer = HttpServer.HttpListener.Create(address, port); } m_httpServer.LogWriter = httpLogger; m_httpServer.RequestReceived += RequestReceivedHandler; m_httpServer.Start(64); m_log.Info("HTTP server is listening at " + m_uri); #endregion Initialization return true; }
public bool Start(System.Net.IPAddress ip, int port) { try { m_listener = HttpListener.Create(httpserverlog, ip, port); m_webdav = new WebDAVListener(m_listener, @"^/inventory/"); m_webdav.Authentication = AuthenticationType.None; m_listener.Start(10); } catch (Exception e) { m_log.ErrorFormat("[WORLDINVENTORY]: Failed to start WebDAV listener on port {0}. Threw excpetion {1}", port, e.ToString()); return false; } string webdavPropertyStrgConnectionString = String.Empty; IConfig config = m_configs.Configs["realXtend"]; if (config != null) { webdavPropertyStrgConnectionString = config.GetString("WebDAVProperyStorageConnectionString"); m_giveFolderContentOnGet = config.GetBoolean("WorldInventoryGetFolderContent", false); m_autoconvertJpgToJ2k = config.GetBoolean("WorldInventoryAutoConvertJpegToJ2K", false); } if (webdavPropertyStrgConnectionString == null || webdavPropertyStrgConnectionString == String.Empty) return false; m_assetFolderStrg = new NHibernateAssetsFolder(); m_propertyMngr = new NHibernateIWebDAVResource(); m_propertyMngr.Initialise(webdavPropertyStrgConnectionString); m_assetFolderStrg.Initialise(webdavPropertyStrgConnectionString); AddRootFolders(); m_webdav.OnPropFind += PropFindHandler; m_webdav.OnGet += GetHandler; m_webdav.OnPut += PutHandler; m_webdav.OnNewCol += MkcolHandler; m_webdav.OnMove += MoveHandler; m_webdav.OnDelete += DeleteHandler; return true; }
public CapsServer(HttpListener httpServer, string handlerPath) { serverOwned = false; capsHandler = BuildCapsHandler(handlerPath); server = httpServer; }
public CapsServer(IPAddress address, int port, X509Certificate sslCertificate, X509Certificate rootCA, bool requireClientCertificate) { this.rootCA = rootCA; serverOwned = true; capsHandler = BuildCapsHandler(@"^/caps/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"); server = HttpListener.Create(log4netLogWriter.Instance, address, port, sslCertificate, SslProtocols.Default, requireClientCertificate); }
public void Start(IPAddress a, int port) { listener = HttpListener.Create(a, port); listener.RequestReceived += listener_RequestReceived; listener.Start(1000); }
public WebDAVListener(HttpListener server, string path) { this.HttpServer = server; OptionsCommand optionsCommand = new OptionsCommand(); optionsCommand.Start(this, path); commands.Add(optionsCommand); PropFindCommand propfindCommand = new PropFindCommand(); propfindCommand.Start(this, path); commands.Add(propfindCommand); LockCommand lockCommand = new LockCommand(); lockCommand.Start(this, path); commands.Add(lockCommand); UnlockCommand unlockCommand = new UnlockCommand(); unlockCommand.Start(this, path); commands.Add(unlockCommand); MkcolCommand mkcolCommand = new MkcolCommand(); mkcolCommand.Start(this, path); commands.Add(mkcolCommand); MoveCommand moveCommand = new MoveCommand(); moveCommand.Start(this, path); commands.Add(moveCommand); GetCommand getCommand = new GetCommand(); getCommand.Start(this, path); commands.Add(getCommand); PutCommand putCommand = new PutCommand(); putCommand.Start(this, path); commands.Add(putCommand); DeleteCommand deleteCommand = new DeleteCommand(); deleteCommand.Start(this, path); commands.Add(deleteCommand); CopyCommand copyCommand = new CopyCommand(); copyCommand.Start(this, path); commands.Add(copyCommand); PropPatchCommand proppatchCommand = new PropPatchCommand(); proppatchCommand.Start(this, path); commands.Add(proppatchCommand); }
protected virtual void Dispose(bool disposing) { if (disposing) { if (listener != null) { listener.Stop(); listener = null; } } }
public bool Start() { IPHostEntry entry; IPAddress address; IConfig httpConfig; #region Config Parsing try { // Load the extension list (and ordering) from our config file ConfigFile = new IniConfigSource(CONFIG_FILE); httpConfig = ConfigFile.Configs["Http"]; IConfig extensionConfig = ConfigFile.Configs["Extensions"]; ExtensionList = new List<string>(extensionConfig.GetKeys()); } catch (Exception) { Logger.Log("Failed to load [Extensions] section from " + CONFIG_FILE, Helpers.LogLevel.Error); return false; } #endregion Config Parsing #region HTTP Server int port = httpConfig.GetInt("ListenPort"); string hostname = httpConfig.GetString("Hostname", null); string sslCertFile = httpConfig.GetString("SSLCertFile", null); if (String.IsNullOrEmpty(hostname)) { hostname = Dns.GetHostName(); entry = Dns.GetHostEntry(hostname); address = IPAddress.Any; } else { entry = Dns.GetHostEntry(hostname); if (entry != null && entry.AddressList.Length > 0) { address = entry.AddressList[0]; } else { Logger.Log("Could not resolve an IP address from hostname " + hostname + ", binding to all interfaces", Helpers.LogLevel.Warning); address = IPAddress.Any; } } if (!String.IsNullOrEmpty(sslCertFile)) { // HTTPS mode X509Certificate serverCert; try { serverCert = X509Certificate.CreateFromCertFile(sslCertFile); } catch (Exception ex) { Logger.Log("Failed to load SSL certificate file \"" + sslCertFile + "\": " + ex.Message, Helpers.LogLevel.Error); return false; } HttpServer = HttpListener.Create(log4netLogWriter.Instance, address, port, serverCert); HttpUri = new Uri("https://" + hostname + (port != 80 ? (":" + port) : String.Empty)); } else { // HTTP mode HttpServer = HttpListener.Create(log4netLogWriter.Instance, address, port); HttpUri = new Uri("http://" + hostname + (port != 80 ? (":" + port) : String.Empty)); } HttpServer.Start(10); Logger.Log("Simian is listening at " + HttpUri.ToString(), Helpers.LogLevel.Info); #endregion HTTP Server #region Server Extensions try { // Create a list of references for .cs extensions that are compiled at runtime List<string> references = new List<string>(); references.Add("OpenMetaverseTypes.dll"); references.Add("OpenMetaverse.dll"); references.Add("Simian.exe"); // Load extensions from the current executing assembly, Simian.*.dll assemblies on disk, and // Simian.*.cs source files on disk. extensions.LoadAllExtensions(Assembly.GetExecutingAssembly(), AppDomain.CurrentDomain.BaseDirectory, ExtensionList, references, "Simian.*.dll", "Simian.*.cs"); // Automatically assign extensions that implement interfaces to the list of interface // variables in "assignables" extensions.AssignExtensions(this, extensions.GetInterfaces(this)); } catch (ExtensionException ex) { Logger.Log("Extension loading failed, shutting down: " + ex.Message, Helpers.LogLevel.Error); Stop(); return false; } foreach (IExtension<Simian> extension in extensions.Extensions) { // Track all of the extensions with persistence if (extension is IPersistable) PersistentExtensions.Add((IPersistable)extension); } // Start all of the extensions foreach (IExtension<Simian> extension in extensions.Extensions) { Logger.Log("Starting Simian extension " + extension.GetType().Name, Helpers.LogLevel.Info); extension.Start(this); } #endregion Server Extensions #region Region Loading try { string[] configFiles = Directory.GetFiles(REGION_CONFIG_DIR, "*.ini", SearchOption.AllDirectories); for (int i = 0; i < configFiles.Length; i++) { // TODO: Support non-SceneManager scenes? ISceneProvider scene = new SceneManager(); #region Config Parsing IniConfigSource source = new IniConfigSource(configFiles[i]); IConfig regionConfig = source.Configs["Region"]; string name = regionConfig.GetString("Name", null); string defaultTerrain = regionConfig.GetString("DefaultTerrain", null); int udpPort = regionConfig.GetInt("UDPPort", 0); uint regionX, regionY; UInt32.TryParse(regionConfig.GetString("RegionX", "0"), out regionX); UInt32.TryParse(regionConfig.GetString("RegionY", "0"), out regionY); string certFile = regionConfig.GetString("RegionCertificate", null); int staticObjectLimit = regionConfig.GetInt("StaticObjectLimit", 0); int physicalObjectLimit = regionConfig.GetInt("PhysicalObjectLimit", 0); float waterHeight = regionConfig.GetFloat("WaterHeight", 0f); RegionFlags regionFlags = RegionFlags.None; if (regionConfig.GetBoolean("AllowDamage")) regionFlags |= RegionFlags.AllowDamage; if (regionConfig.GetBoolean("SunFixed")) regionFlags |= RegionFlags.SunFixed; if (regionConfig.GetBoolean("BlockTerraform")) regionFlags |= RegionFlags.BlockTerraform; if (regionConfig.GetBoolean("SkipScripts")) regionFlags |= RegionFlags.SkipScripts; if (regionConfig.GetBoolean("SkipPhysics")) regionFlags |= RegionFlags.SkipPhysics; if (regionConfig.GetBoolean("PublicAllowed")) regionFlags |= RegionFlags.PublicAllowed; if (regionConfig.GetBoolean("NoFly")) regionFlags |= RegionFlags.NoFly; if (regionConfig.GetBoolean("AllowDirectTeleport")) regionFlags |= RegionFlags.AllowDirectTeleport; if (regionConfig.GetBoolean("RestrictPushObject")) regionFlags |= RegionFlags.RestrictPushObject; if (regionConfig.GetBoolean("AllowParcelChanges")) regionFlags |= RegionFlags.AllowParcelChanges; if (String.IsNullOrEmpty(name) || regionX == 0 || regionY == 0 || String.IsNullOrEmpty(certFile)) { Logger.Log("Incomplete information in " + configFiles[i] + ", skipping", Helpers.LogLevel.Warning); continue; } // TODO: Real map tile image generation, perhaps? UUID mapTextureID = new UUID("89556747-24cb-43ed-920b-47caed15465f"); #endregion Config Parsing #region IPEndPoint Assignment IPEndPoint endpoint; if (udpPort != 0) { endpoint = new IPEndPoint(address, udpPort); } else { udpPort = DEFAULT_UDP_PORT; while (true) { endpoint = new IPEndPoint(address, udpPort); Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); try { udpSocket.Bind(endpoint); udpSocket.Close(); break; } catch (SocketException) { ++udpPort; } } } // Make sure 0.0.0.0 gets replaced with a valid IP address if (endpoint.Address == IPAddress.Any) endpoint.Address = entry.AddressList.Length > 0 ? entry.AddressList[entry.AddressList.Length - 1] : IPAddress.Loopback; #endregion IPEndPoint Assignment #region Grid Registration X509Certificate2 regionCert; try { regionCert = new X509Certificate2(DATA_DIR + certFile); } catch (Exception) { Logger.Log("Failed to load region certificate file from " + certFile, Helpers.LogLevel.Error); continue; } RegionInfo regionInfo = new RegionInfo(); regionInfo.Handle = Utils.UIntsToLong(256 * regionX, 256 * regionY); regionInfo.HttpServer = HttpUri; regionInfo.IPAndPort = endpoint; regionInfo.Name = name; regionInfo.MapTextureID = mapTextureID; regionInfo.Flags = regionFlags; regionInfo.AgentCount = 0; regionInfo.WaterHeight = waterHeight; regionInfo.Online = true; // Create a capability for other regions to initiate a client connection to this region regionInfo.EnableClientCap = Capabilities.CreateCapability(scene.EnableClientCapHandler, false, null); if (!Grid.TryRegisterGridSpace(regionInfo, regionCert, out regionInfo.ID)) { Logger.Log("Failed to register grid space for region " + name, Helpers.LogLevel.Error); continue; } #endregion Grid Registration scene.Start(this, regionInfo, regionCert, defaultTerrain, staticObjectLimit, physicalObjectLimit); Scenes.Add(scene); } } catch (Exception ex) { Logger.Log("Failed to load region config files: " + ex.Message, Helpers.LogLevel.Error); return false; } #endregion Region Loading return true; }
public CapsServer(IPAddress address, int port) { serverOwned = true; capsHandler = BuildCapsHandler(@"^/caps/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"); server = HttpListener.Create(log4netLogWriter.Instance, address, port); }
/// <summary> /// Starts this UPnP control point. All device templates should be configured at the time this method gets called. /// The network tracker must be started after this method is called, else we might miss some connect events. /// </summary> public void Start() { lock (_cpData.SyncObj) { if (_isActive) throw new IllegalCallException("UPnP control point mustn't be started multiple times"); if (UPnPConfiguration.USE_IPV4) { _httpListenerV4 = HttpListener.Create(IPAddress.Any, 0); _httpListenerV4.RequestReceived += OnHttpListenerRequestReceived; try { _httpListenerV4.Start(DEFAULT_HTTP_REQUEST_QUEUE_SIZE); // Might fail if IPv4 isn't installed _cpData.HttpPortV4 = _httpListenerV4.LocalEndpoint.Port; } catch (SocketException e) { _httpListenerV4 = null; _cpData.HttpPortV4 = 0; UPnPConfiguration.LOGGER.Warn("UPnPControlPoint: Error starting HTTP server (IPv4)", e); } } else { _httpListenerV4 = null; _cpData.HttpPortV4 = 0; } if (UPnPConfiguration.USE_IPV6) { _httpListenerV6 = HttpListener.Create(IPAddress.IPv6Any, 0); _httpListenerV6.RequestReceived += OnHttpListenerRequestReceived; try { _httpListenerV6.Start(DEFAULT_HTTP_REQUEST_QUEUE_SIZE); // Might fail if IPv6 isn't installed _cpData.HttpPortV6 = _httpListenerV6.LocalEndpoint.Port; } catch (SocketException e) { _httpListenerV6 = null; _cpData.HttpPortV6 = 0; UPnPConfiguration.LOGGER.Warn("UPnPControlPoint: Error starting HTTP server (IPv6)", e); } } else { _httpListenerV6 = null; _cpData.HttpPortV6 = 0; } _networkTracker.RootDeviceRemoved += OnRootDeviceRemoved; _networkTracker.DeviceRebooted += OnDeviceRebooted; _isActive = true; } }
private void startHTTP(int port) { if(server != null) { server.Stop(); } server = HttpListener.Create(IPAddress.Any, port); server.RequestReceived += http_onRequest; server.ExceptionThrown += new ExceptionHandler(server_ExceptionThrown); server.Start(5); toolStripStatusLabel1.Text = "Serveur HTTP démarré sur le port "+port.ToString(); }
private void StartHTTP() { try { //m_httpListener = new HttpListener(); NotSocketErrors = 0; if (!m_ssl) { //m_httpListener.Prefixes.Add("http://+:" + m_port + "/"); //m_httpListener.Prefixes.Add("http://10.1.1.5:" + m_port + "/"); m_httpListener2 = CoolHTTPListener.Create(m_listenIPAddress, (int)m_port); m_httpListener2.ExceptionThrown += httpServerException; m_httpListener2.LogWriter = httpserverlog; // Uncomment this line in addition to those in HttpServerLogWriter // if you want more detailed trace information from the HttpServer //m_httpListener2.UseTraceLogs = true; //m_httpListener2.DisconnectHandler = httpServerDisconnectMonitor; } else { //m_httpListener.Prefixes.Add("https://+:" + (m_sslport) + "/"); //m_httpListener.Prefixes.Add("http://+:" + m_port + "/"); m_httpListener2 = CoolHTTPListener.Create(IPAddress.Any, (int)m_port, m_cert); m_httpListener2.ExceptionThrown += httpServerException; m_httpListener2.LogWriter = httpserverlog; } m_httpListener2.RequestReceived += OnRequest; //m_httpListener.Start(); m_httpListener2.Start(64); // Long Poll Service Manager with 3 worker threads a 25 second timeout for no events m_PollServiceManager = new PollServiceRequestManager(this, 3, 25000); HTTPDRunning = true; //HttpListenerContext context; //while (true) //{ // context = m_httpListener.GetContext(); // ThreadPool.UnsafeQueueUserWorkItem(new WaitCallback(HandleRequest), context); // } } catch (Exception e) { m_log.Error("[BASE HTTP SERVER]: Error - " + e.Message); m_log.Error("[BASE HTTP SERVER]: Tip: Do you have permission to listen on port " + m_port + ", " + m_sslport + "?"); // We want this exception to halt the entire server since in current configurations we aren't too // useful without inbound HTTP. throw e; } }
public virtual void Start() { try { listener = HttpListener.Create(Ip, Port); listener.RequestReceived += OnRequest; listener.Start(int.MaxValue); tokenBucketTimer = new Timer((e) => { DegradeBucket(); }, null, TimeSpan.Zero, TimeSpan.FromMinutes(Math.Max(TShock.Config.RESTRequestBucketDecreaseIntervalMinutes, 1))); } catch (Exception ex) { TShock.Log.Error("Fatal Startup Exception"); TShock.Log.Error(ex.ToString()); TShock.Log.ConsoleError("Invalid REST configuration: \nYou may already have a REST service bound to port {0}. \nPlease adjust your configuration and restart the server. \nPress any key to exit.", Port); Console.ReadLine(); Environment.Exit(1); } }
private void StartHTTP() { m_log.InfoFormat( "[BASE HTTP SERVER]: Starting {0} server on port {1}", UseSSL ? "HTTPS" : "HTTP", Port); try { //m_httpListener = new HttpListener(); NotSocketErrors = 0; if (!m_ssl) { //m_httpListener.Prefixes.Add("http://+:" + m_port + "/"); //m_httpListener.Prefixes.Add("http://10.1.1.5:" + m_port + "/"); m_httpListener2 = CoolHTTPListener.Create(m_listenIPAddress, (int)m_port); m_httpListener2.ExceptionThrown += httpServerException; m_httpListener2.LogWriter = httpserverlog; // Uncomment this line in addition to those in HttpServerLogWriter // if you want more detailed trace information from the HttpServer //m_httpListener2.UseTraceLogs = true; //m_httpListener2.DisconnectHandler = httpServerDisconnectMonitor; } else { //m_httpListener.Prefixes.Add("https://+:" + (m_sslport) + "/"); //m_httpListener.Prefixes.Add("http://+:" + m_port + "/"); m_httpListener2 = CoolHTTPListener.Create(IPAddress.Any, (int)m_port, m_cert); m_httpListener2.ExceptionThrown += httpServerException; m_httpListener2.LogWriter = httpserverlog; } m_httpListener2.RequestReceived += OnRequest; //m_httpListener.Start(); m_httpListener2.Start(64); // Long Poll Service Manager with 3 worker threads a 25 second timeout for no events m_PollServiceManager = new PollServiceRequestManager(this, 3, 25000); m_PollServiceManager.Start(); HTTPDRunning = true; //HttpListenerContext context; //while (true) //{ // context = m_httpListener.GetContext(); // ThreadPool.UnsafeQueueUserWorkItem(new WaitCallback(HandleRequest), context); // } } catch (Exception e) { m_log.Error("[BASE HTTP SERVER]: Error - " + e.Message); m_log.Error("[BASE HTTP SERVER]: Tip: Do you have permission to listen on port " + m_port + ", " + m_sslport + "?"); // We want this exception to halt the entire server since in current configurations we aren't too // useful without inbound HTTP. throw e; } m_requestsProcessedStat = new Stat( "HTTPRequestsServed", "Number of inbound HTTP requests processed", "", "requests", "httpserver", Port.ToString(), StatType.Pull, MeasuresOfInterest.AverageChangeOverTime, stat => stat.Value = RequestNumber, StatVerbosity.Debug); StatsManager.RegisterStat(m_requestsProcessedStat); }
private void StartHTTP() { try { //m_httpListener = new HttpListener(); NotSocketErrors = 0; if (!m_isSecure) { //m_httpListener.Prefixes.Add("http://+:" + m_port + "/"); //m_httpListener.Prefixes.Add("http://10.1.1.5:" + m_port + "/"); m_httpListener = HttpListener.Create(m_listenIPAddress, (int)m_port/*, httpserverlog*/); m_httpListener.ExceptionThrown += httpServerException; m_httpListener.LogWriter = httpserverlog; // Uncomment this line in addition to those in HttpServerLogWriter // if you want more detailed trace information from the HttpServer //m_httpListener2.UseTraceLogs = true; //m_httpListener2.DisconnectHandler = httpServerDisconnectMonitor; } else { m_httpListener = HttpListener.Create(IPAddress.Any, (int)m_port, m_cert, m_sslProtocol); m_httpListener.ExceptionThrown += httpServerException; m_httpListener.LogWriter = httpserverlog; } m_httpListener.RequestReceived += OnRequest; m_httpListener.Start(64); // Long Poll Service Manager with 3 worker threads a 25 second timeout for no events m_PollServiceManager = new PollServiceRequestManager(this, 3, 25000); HTTPDRunning = true; } catch (Exception e) { MainConsole.Instance.Error("[BASE HTTP SERVER]: Error - " + e.Message); MainConsole.Instance.Error("[BASE HTTP SERVER]: Tip: Do you have permission to listen on port " + m_port + "?"); // We want this exception to halt the entire server since in current configurations we aren't too // useful without inbound HTTP. throw; } }
public HttpView(Field field) { _field = field; _listener = HttpListener.Create(System.Net.IPAddress.Any, 8080); _listener.RequestReceived += OnRequest; _listener.Start(5); }
static void Main(string[] args) { engine = new VMExecutionEngine(); HttpListener mlist = new HttpListener(80); mlist.onClientConnect += new HttpListener.ConnectEventDgate(mlist_onClientConnect); mimemappings.Add(".htm", "text/html"); mimemappings.Add(".jpg", "image/jpeg"); mimemappings.Add(".html", "text/html"); mimemappings.Add(".png", "image/png"); mimemappings.Add(".js", "text/javascript"); mimemappings.Add(".mp4", "video/mp4"); mimemappings.Add(".ogg", "audio/ogg"); mimemappings.Add(".ogv", "video/ogg"); mimemappings.Add(".swf","application/x-shockwave-flash"); }