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); } } }
private static void Main(string[] args) { HttpListener listener = HttpListener.Create(IPAddress.Any, 8089); listener.RequestReceived += OnRequest; listener.Start(5); Thread.Sleep(9000000); }
/// <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; } }
/// <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() { server.AddHandler(capsHandler); if (serverOwned) { server.Start(10); } }
public virtual void Start() { if (listener == null) { listener = HttpListener.Create(Ip, Port); listener.RequestReceived += OnRequest; listener.Start(int.MaxValue); } }
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); }
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); }
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); }
/// <summary> /// Engine keeps the HTTP server running. /// </summary> private void Engine() { try { _listener.RequestHandler += OnHttpRequest; _listener.Start(QueueSize); _log.InfoFormat("[{0}] HTTP server started", EngineID); lock (_syncObject) Monitor.Wait(_syncObject); } catch (Exception ex) { _log.DebugFormat("[{0}] HTTP server startup failed: {1}", EngineID, ex.ToString()); } _log.InfoFormat("[{0}] HTTP server terminated", EngineID); }
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); } }
/// <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); } }
/// <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); } }
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); } } }
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(); }
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); }
/// <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 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); } }
/// <summary> /// Starts this UPnP server, i.e. starts a network listener and sends notifications about provided devices. /// </summary> /// <param name="advertisementInterval">Interval in seconds to repeat UPnP advertisements in the network. /// The UPnP architecture document (UPnP-arch-DeviceArchitecture-v1 1-20081015, 1.2.2, page 21) states a /// minimum of 1800 seconds. But in the world of today, that value is much to high for many applications and in many /// cases, a value of much less than 1800 seconds is choosen. For servers which will frequently change their /// availability, this value should be short, for more durable serves, this interval can be much longer (maybe a day).</param> public void Bind(int advertisementInterval = UPnPConsts.DEFAULT_ADVERTISEMENT_EXPIRATION_TIME) { lock (_serverData.SyncObj) { if (_serverData.IsActive) { throw new IllegalCallException("UPnP subsystem mustn't be started multiple times"); } _serverData.HTTP_PORTv4 = 0; if (UPnPConfiguration.USE_IPV4) { foreach (IPAddress address in NetworkHelper.GetBindableIPAddresses(AddressFamily.InterNetwork, UPnPConfiguration.IP_ADDRESS_BINDINGS)) { HttpListener httpListenerV4 = HttpListener.Create(address, _serverData.HTTP_PORTv4); httpListenerV4.RequestReceived += OnHttpListenerRequestReceived; try { httpListenerV4.Start(DEFAULT_HTTP_REQUEST_QUEUE_SIZE); // Might fail if IPv4 isn't installed _serverData.HTTP_PORTv4 = httpListenerV4.LocalEndpoint.Port; UPnPConfiguration.LOGGER.Info("UPnP server: HTTP listener for IPv4 protocol started on port {0}", _serverData.HTTP_PORTv4); _serverData.HTTPListeners.Add(httpListenerV4); } catch (SocketException e) { UPnPConfiguration.LOGGER.Warn("UPnPServer: Error starting HTTP server (IPv4)", e); } } } else { UPnPConfiguration.LOGGER.Info("UPnP server: IPv4 protocol disabled, so no HTTP listener started for IPv4"); } _serverData.HTTP_PORTv6 = 0; if (UPnPConfiguration.USE_IPV6) { foreach (IPAddress address in NetworkHelper.GetBindableIPAddresses(AddressFamily.InterNetworkV6, UPnPConfiguration.IP_ADDRESS_BINDINGS)) { HttpListener httpListenerV6 = HttpListener.Create(address, _serverData.HTTP_PORTv6); // Might fail if IPv6 isn't installed httpListenerV6.RequestReceived += OnHttpListenerRequestReceived; try { httpListenerV6.Start(DEFAULT_HTTP_REQUEST_QUEUE_SIZE); _serverData.HTTP_PORTv6 = httpListenerV6.LocalEndpoint.Port; UPnPConfiguration.LOGGER.Info("UPnP server: HTTP listener for IPv6 protocol started at port {0}", _serverData.HTTP_PORTv6); _serverData.HTTPListeners.Add(httpListenerV6); } catch (SocketException e) { UPnPConfiguration.LOGGER.Warn("UPnPServer: Error starting HTTP server (IPv6)", e); } } } else { UPnPConfiguration.LOGGER.Info("UPnP server: IPv6 protocol disabled, so no HTTP listener started for IPv6"); } _serverData.SSDPController = new SSDPServerController(_serverData) { AdvertisementExpirationTime = advertisementInterval }; _serverData.GENAController = new GENAServerController(_serverData); InitializeDiscoveryEndpoints(); NetworkChange.NetworkAddressChanged += OnNetworkAddressChanged; _serverData.IsActive = true; // At the end, start the controllers _serverData.SSDPController.Start(); _serverData.GENAController.Start(); UPnPConfiguration.LOGGER.Info("UPnP server online hosting {0} UPnP root devices", _serverData.Server.RootDevices.Count); } }
public void Start(IPAddress a, int port) { listener = HttpListener.Create(a, port); listener.RequestReceived += listener_RequestReceived; listener.Start(1000); }
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 void Start() { _http.Start(); Task.Run(() => { while (_http.IsListening) { try { var context = _http.GetContext(); var req = context.Request; var res = context.Response; Console.WriteLine($"[{DateTime.Now.ToLongTimeString()}] {req.HttpMethod}: {req.RawUrl} from {req.RemoteEndPoint.Address}"); if (req.HttpMethod == "GET") { switch (req.RawUrl) { case "/data": SendJson(res, JsonConvert.SerializeObject(new Animal() { Id = Guid.NewGuid(), Name = "Vaska", Type = "Cat", Age = 0.3f })); break; case "/all": SendJson(res, JsonConvert.SerializeObject(_db.GetAllAnimalsAsync().Result)); break; default: SendHtml(res, "Hello. Make GET /data to get json"); break; } } else if (req.HttpMethod == "POST") { var buffer = new byte[req.ContentLength64]; req.InputStream.ReadAsync(buffer, 0, buffer.Length); var incoming = _encoding.GetString(buffer); Console.WriteLine($"Received data: {incoming}"); switch (req.RawUrl) { case "/me": { var token = JsonConvert.DeserializeObject <int>(incoming); var person = _cache.GetPersonAsync(token).Result; if (person == null) { SendHtml(res, "We don't know you"); } else { var animals = _db.GetTakenAnimalsByAsync(person); SendJson(res, JsonConvert.SerializeObject(animals.Result)); } } break; case "/mebyemail": { var email = JsonConvert.DeserializeObject <string>(incoming); var token = email.GetHashCode(); var person = _cache.GetPersonAsync(token).Result; if (person == null) { SendHtml(res, "We don't know you"); } else { var animals = _db.GetTakenAnimalsByAsync(person); SendJson(res, JsonConvert.SerializeObject(animals.Result)); } } break; case "/add": { var animal = JsonConvert.DeserializeObject <Animal>(incoming); if (animal == null) { SendHtml(res, "Error: couldn't deserialize given Animal"); } else { _db.AddAnimalAsync(animal); SendHtml(res, "Animal added successfully"); } } break; case "/request": { var person = JsonConvert.DeserializeObject <Person>(incoming); var token = person.Email.GetHashCode(); _cache.AddPersonAsync(token, person); _db.TakeAnimalAsync(person); SendJson(res, JsonConvert.SerializeObject(token)); } break; default: SendHtml(res, "Hello. Make GET /data to get json"); break; } } //SendHtml(res, $"Congratulations, {person.Name}! Pet with ID#{person.PetID} is ordered by you!"); } catch (Exception e) { Console.WriteLine(e.Message); } } }); Console.WriteLine($"\nServer is listening to http://{_ip}:{_port}..."); }
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); }
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 static void Main(string[] args) { var listener = new HttpListener(); listener.Prefixes.Add("http://localhost:5000/"); listener.Start(); while (true) { var context = listener.GetContext(); var output = context.Response.OutputStream; var writer = new StreamWriter(output); var req = context.Request; object data = "No data"; if (req.Url.Segments[1].Contains("developers")) { data = new string[] { "Shafag", "Zulfugar", "Javid", "Oqtay", "Alim" }; } else if (req.Url.Segments[1].Contains("designers")) { if (req.Url.Segments[2].Contains("fake")) { data = new string[] { "Sasha" }; } else if (req.Url.Segments[2].Contains("actual")) { data = new string[] { "Elkhan", "Isa", "Nadir" }; } } writer.WriteLine(JsonConvert.SerializeObject(data)); writer.Close(); context.Response.StatusCode = 200; context.Response.Close(); //var context = listener.GetContext(); //if (context.Request.HttpMethod.ToUpper() != "POST") { // Console.WriteLine("not post"); // context.Response.StatusCode = 404; // context.Response.Close(); // continue; //} //if (context.Request.ContentLength64 == 0) { // Console.WriteLine("no data"); // context.Response.StatusCode = 403; // context.Response.Close(); // continue; //} //var stream = context.Request.InputStream; //var reader = new StreamReader(stream); //var str = reader.ReadLine(); //var msg = JsonConvert.DeserializeObject<MessageItem>(str); //if (msg == null) { // Console.WriteLine("invalid data"); // context.Response.StatusCode = 403; // context.Response.Close(); // continue; //} //Console.WriteLine($"{msg.Name}: {msg.Message}"); //var output = context.Response.OutputStream; //var writer = new StreamWriter(output); //var data = new { // Result = "MessageProcessed", // StatusCode = 200, // OperationTime = DateTime.Now //}; //writer.WriteLine(JsonConvert.SerializeObject(data)); //writer.Close(); //context.Response.StatusCode = 200; //context.Response.Close(); } }
public void Start() { listener = new HttpListener(); if (!HttpListener.IsSupported) { return; } listener.Prefixes.Add(ip); try { listener.Start(); Console.WriteLine("Server started successfully"); } catch (Exception e) { Console.WriteLine(e.Message); Console.ReadLine(); } while (listener.IsListening) { Console.WriteLine("Waiting for request.."); HttpListenerContext context = listener.GetContext(); Console.WriteLine("Request received"); Console.WriteLine(context.Request.RemoteEndPoint); // receive incoming request HttpListenerRequest request = context.Request; if (request.HttpMethod == "POST") { ShowRequestData(request); } if (!flag) { return; } //string responseString = @"<!DOCTYPE HTML> // <html><head></head><body> // <form method=""post"" action=""""> // <p><b>Name: </b><br> // <input type=""text"" name=""myname"" size=""40""></p> // <p><input type=""submit"" value=""send""></p> // </form></body></html>"; //HttpListenerResponse response = context.Response; //response.ContentType = "text/html; charset=UTF-8"; //byte[] buffer = Encoding.UTF8.GetBytes(responseString); //response.ContentLength64 = buffer.Length; HttpListenerResponse response = context.Response; TextReader tr = new StreamReader("data.json"); string msg = tr.ReadToEnd(); byte[] buffer = Encoding.UTF8.GetBytes(msg); response.ContentType = "application/json"; response.ContentLength64 = buffer.Length; using (Stream output = response.OutputStream) { output.Write(buffer, 0, buffer.Length); } } }
public HttpView(Field field) { _field = field; _listener = HttpListener.Create(System.Net.IPAddress.Any, 8080); _listener.RequestReceived += OnRequest; _listener.Start(5); }