public ApiManager() { string hostName = Dns.GetHostName(); string IP = Dns.GetHostByName(hostName).AddressList[0].ToString(); string DebugPort = ConfigurationManager.AppSettings["DebugPort"]; m_vListener = new HttpListener(); if (Convert.ToBoolean(ConfigurationManager.AppSettings["DebugModeLocal"])) { m_vListener.Prefixes.Add("http://localhost:" + DebugPort + "/debug/"); //m_vListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous; m_vListener.Start(); Console.WriteLine("API Manager started on http://localhost:" + DebugPort + "/debug/"); Action action = RunServer; action.BeginInvoke(RunServerCallback, action); } else { string DebugMode = IP + ":"; m_vListener.Prefixes.Add("http://" + DebugMode + DebugPort + "/debug/"); //m_vListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous; m_vListener.Start(); Console.WriteLine("API Manager started on http://" + IP + ":" + DebugPort + "/debug/"); Action action = RunServer; action.BeginInvoke(RunServerCallback, action); } }
private static void Main(string[] args) { var listener = new System.Net.HttpListener(); listener.Prefixes.Add("http://localhost:8080/"); listener.Prefixes.Add("http://127.0.0.1:8080/"); listener.Start(); while (true) { try { var context = listener.GetContext(); //Block until a connection comes in context.Response.StatusCode = 200; context.Response.SendChunked = true; var bytes = Encoding.UTF8.GetBytes("Hue Hue Hue\n"); context.Response.OutputStream.Write(bytes, 0, bytes.Length); context.Response.Close(); } catch (Exception) { // Client disconnected or some other error - ignored for this example } } }
static void Main(string[] args) { if(args.Length != 1) { Console.Error.WriteLine("Usage: name port"); return; } int port; if(!int.TryParse(args[0], out port)) { Console.Error.WriteLine("Invalid port"); return; } var listener = new HttpListener(); listener.Prefixes.Add(string.Format("http://+:{0}/sort/", port)); listener.Start(); while(true) { SolveAsync(listener.GetContext()); } }
public static HttpListener CreateAndStartListener (string prefix) { HttpListener listener = new HttpListener (); listener.Prefixes.Add (prefix); listener.Start (); return listener; }
public DetergentHttpListener( string uriPrefix, string applicationPath, IDetergentHttpHandler detergentHttpHandler) { if (uriPrefix == null) throw new ArgumentNullException("uriPrefix"); if (applicationPath == null) throw new ArgumentNullException("applicationPath"); if (detergentHttpHandler == null) throw new ArgumentNullException("detergentHttpHandler"); this.uriPrefix = uriPrefix; this.applicationPath = applicationPath; this.detergentHttpHandler = detergentHttpHandler; httpListener = new HttpListener(); applicationRootUrl = new Uri(new Uri(uriPrefix), applicationPath).ToString(); if (false == applicationRootUrl.EndsWith("/", StringComparison.OrdinalIgnoreCase)) applicationRootUrl = applicationRootUrl + '/'; httpListener.Prefixes.Add(applicationRootUrl); DumpDiagnostics(); httpListener.Start(); IAsyncResult result = httpListener.BeginGetContext(WebRequestCallback, httpListener); }
public HTTPServer() { listener = new HttpListener(); listener.Prefixes.Add("http://*:" + WebAPI.dis.Configuration.Instance.Port + "/"); listener.Start(); WhitelistIPs = new List<string>() { }; if(WebAPI.dis.Configuration.Instance.WhitelistIPs.Count > 0) { foreach(var ip in WebAPI.dis.Configuration.Instance.WhitelistIPs) { WhitelistIPs.Add(ip.IP); } } AsyncCallback callback = null; callback = ar => { if (!listener.IsListening) return; new Thread(() => { this.ProcessClient( listener.EndGetContext(ar) ); }).Start(); listener.BeginGetContext(callback, null); }; listener.BeginGetContext(callback, null); }
public void Run () { mainScheduler = TaskScheduler.FromCurrentSynchronizationContext (); Task.Run (() => { var url = "http://+:" + port + "/"; var remTries = 2; while (remTries > 0) { remTries--; listener = new HttpListener (); listener.Prefixes.Add (url); try { listener.Start (); remTries = 0; } catch (HttpListenerException ex) { if (remTries == 1 && ex.ErrorCode == 5) { // Access Denied GrantServerPermission (url); } else { throw; } } } Loop (); }); }
public void Start() { if (_isStarted) { return; } if (Port == 0) { throw new Exception("Порт не инициализирован"); } if (String.IsNullOrEmpty(Address)) { throw new Exception("Адрес не инициализирован"); } var prefix = String.Format("http://{0}:{1}/", Address, Port); _listener = new System.Net.HttpListener(); _listener.Prefixes.Add(prefix); _listener.Start(); for (int i = 0; i < MaxConnections; i++) { AddConnectionForListener(); } _isStarted = true; }
public void GetContext2 () { HttpListener listener = new HttpListener (); listener.Start (); // "Please call AddPrefix () before calling this method" listener.GetContext (); }
public static void Main(string[] args) { if (!HttpListener.IsSupported) { Console.WriteLine ("HttpListener not available."); Environment.Exit (-1); } var bytecode = ProgramBytecode (); if (bytecode == null) { Environment.Exit (-1); } HttpListener hl = new HttpListener (); hl.Prefixes.Add ("http://localhost:8080/"); hl.Start (); var requestNo = 1; var fsd = new FileSystemDatabase ("db"); while (hl.IsListening) { var ctx = hl.GetContext (); Console.WriteLine ("Serving a request ({0} {1}).", requestNo, ctx.Request.Url.AbsolutePath); if (ctx.Request.Url.AbsolutePath == "/") { ServeGuessNumberRequest (ctx, fsd); } else { ctx.Response.OutputStream.Close (); } Console.WriteLine ("Served a request ({0}).", requestNo); requestNo++; } }
// Methods protected override Task ExecuteAsync(CancellationToken stoppingToken) { return(Task.Run(() => { // Variables HttpListener httpListener = null; HttpListenerContext httpContext = null; // Execute try { // HttpListener httpListener = new System.Net.HttpListener(); httpListener.Prefixes.Add(@"http://*****:*****@"{amount:500}"); streamWriter.Close(); } httpContext.Response.Close(); } finally { // Dispose Thread.Sleep(1000); httpListener?.Stop(); httpListener?.Close(); } })); }
LdtpdService() { if (!String.IsNullOrEmpty(ldtpDebugEnv)) debug = true; if (String.IsNullOrEmpty(ldtpPort)) ldtpPort = "4118"; common = new Common(debug); windowList = new WindowList(common); listener = new HttpListener(); listener.Prefixes.Add("http://localhost:" + ldtpPort + "/"); listener.Prefixes.Add("http://+:" + ldtpPort + "/"); // Listen on all possible IP address if (listenAllInterface != null && listenAllInterface.Length > 0) { if (debug) Console.WriteLine("Listening on all interface"); listener.Prefixes.Add("http://*:" + ldtpPort + "/"); } else { // For Windows 8, still you need to add firewall rules // Refer: README.txt if (debug) Console.WriteLine("Listening only on local interface"); } listener.Start(); svc = new Core(windowList, common, debug); }
public HttpServer(string baseDirectory) { this.baseDirectory = baseDirectory; var rnd = new Random(); for (int i = 0; i < 100; i++) { int port = rnd.Next(49152, 65536); try { listener = new HttpListener(); listener.Prefixes.Add("http://localhost:" + port + "/"); listener.Start(); this.port = port; listener.BeginGetContext(ListenerCallback, null); return; } catch (Exception x) { listener.Close(); Debug.WriteLine("HttpListener.Start:\n" + x); } } throw new ApplicationException("Failed to start HttpListener"); }
private static void OpenFakeHttpServer(int port) { Console.WriteLine($"Openning port {port}"); int i = 0; var li = new HttpListener(); li.Prefixes.Add($"http://+:{port}/api/"); li.Start(); Task.Factory.StartNew(() => { while (true) { var ctx = li.GetContext(); using (ctx.Response) { ctx.Response.SendChunked = false; ctx.Response.StatusCode = 200; Console.WriteLine($"at {port} Correlation {ctx.Request.Headers["X-CORRELATION"]}"); using (var sw = new StreamWriter(ctx.Response.OutputStream)) { ++i; var str = $"{i}!!!"; ctx.Response.ContentLength64 = str.Length; sw.Write(str); } } } }); }
static void HttpServer() { listener = new HttpListener(); listener.Prefixes.Add("http://*:5000/"); listener.Start(); while (true) { var context = listener.GetContext(); var request = context.Request; var response = context.Response; var tw = new StreamWriter(response.OutputStream); var path = request.Url.AbsolutePath; if (path.StartsWith("/type/")) { ShowInstancesOf(tw, path.Substring(6)); } else { Summary(tw); } tw.Flush(); response.OutputStream.Close(); } }
public void Start() { var listener = new System.Net.HttpListener(); listener.Prefixes.Add("http://localhost:1234/"); listener.Start(); var t = new Thread(_ => { while (true) { var context = listener.GetContext(); // get te context this.ExecutePipe(context); if (context.Request.HttpMethod == "GET") { _gets.GetOrIgnore(context.Request.Url.AbsolutePath)?.Invoke(context.Request, context.Response); } if (context.Request.HttpMethod == "POST") { _posts.GetOrIgnore(context.Request.Url.AbsolutePath)?.Invoke(context.Request, context.Response); } } }); t.Start(); }
static void Main(string[] args) { listener = new HttpListener(); listener.Prefixes.Add("http://*:" + port + "/"); //add IP of your website to link to gold purchase OR leave blank and create your own hard-coded website! listener.Start(); //Server will freak out if you don't have admin permissions listen = new Thread(ListenerCallback); listen.Start(); for (var i = 0; i < workers.Length; i++) { workers[i] = new Thread(Worker); workers[i].Start(); } Console.CancelKeyPress += (sender, e) => { Console.WriteLine("Terminating..."); listener.Stop(); while (contextQueue.Count > 0) Thread.Sleep(100); Environment.Exit(0); }; Console.ForegroundColor = ConsoleColor.Green; Console.Title = "Database Server"; Console.WriteLine("Connection Successful at Port " + port + "."); XmlDatas.behaviors = false; XmlDatas.DoSomething(); Thread.CurrentThread.Join(); }
public void Start() { httpListener = new HttpListener(); httpListener.Prefixes.Add("http://localhost:" + this.ListenPort + "/"); httpListener.Start(); httpListener.BeginGetContext(this.OnNewRequest, null); }
/// <summary> /// Http监听器 /// </summary> /// <param name="host">监听host</param> /// <param name="port">监听端口</param> public HttpListener(string host = "*", int port = 9478) { listener = new Listener(); listener.Prefixes.Add("http://" + host + ":" + port + "/"); listener.Start(); listener.BeginGetContext(ListenedRequest, null); }
/// <summary> /// 启动 /// </summary> public async void StartAsync() { var listener = new System.Net.HttpListener(); listener.Prefixes.Add($"http://{_endPoint.ToString()}/GarbageBin/Data/"); // 启动服务器 try { listener.Start(); } catch (Exception ex) { Console.WriteLine($"智慧垃圾桶,启动服务器失败,{ex.ToString()}"); return; } // 消息接收 while (true) { try { var context = await listener.GetContextAsync(); var result = await ReceiveMessage(context); await SendResponse(context, result); } catch (Exception ex) { Console.WriteLine($"智慧垃圾桶,获取请求失败,{ex.ToString()}"); } } }
public override void Run() { Trace.WriteLine("WorkerRole entry point called", "Information"); HttpListener listener = new HttpListener(); IPEndPoint inputEndPoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["HelloWorldEndpoint"].IPEndpoint; string listenerPrefix = string.Format(CultureInfo.InvariantCulture, "http://{0}:{1}/", inputEndPoint.Address, inputEndPoint.Port); Trace.WriteLine("Listening to -" + listenerPrefix); listener.Prefixes.Add(listenerPrefix); listener.Start(); while (true) { // Note: The GetContext method blocks while waiting for a request. HttpListenerContext context = listener.GetContext(); // Obtain a response object. HttpListenerResponse response = context.Response; // Construct a response. string responseString = "<HTML><BODY> Hello world!</BODY></HTML>"; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); // Get a response stream and write the response to it. response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); //Close the output stream. output.Close(); } }
private async Task StartServer() { HttpServ = new HttpListener(); btnStartHttpServ.Text = "Stop Server"; HttpServ.Prefixes.Add("http://localhost:" + txtHttpPort.Value.ToString() + "/"); HttpServ.Start(); txtHttpLog.Text += "Start Listining on Port :" + txtHttpPort.Value + "\r\n"; txtHttpLog.Text += "Server is Running...\r\n\r\n"; while (true) { try { var ctx = await HttpServ.GetContextAsync(); txtHttpLog.Text += "Request: " + ctx.Request.Url.AbsoluteUri + "\r\n"; var page = Application.StartupPath + "\\wwwroot" + ctx.Request.Url.LocalPath; if (File.Exists(page)) { string file; var ext = new FileInfo(page); if (ext.Extension == ".php") { file = ProcessPhpPage(PhpCompilerPath, page); txtHttpLog.Text += "Processing php page...\r\n"; } else { file = File.ReadAllText(page); } await ctx.Response.OutputStream.WriteAsync(ASCIIEncoding.UTF8.GetBytes(file), 0, file.Length); ctx.Response.OutputStream.Close(); ctx.Response.Close(); txtHttpLog.Text += "Response: 200 OK\r\n\r\n"; } else { ctx.Response.StatusCode = 404; var file = "<h2 style=\"color:red;\">404 File Not Found !!!</h2>"; await ctx.Response.OutputStream.WriteAsync(ASCIIEncoding.UTF8.GetBytes(file), 0, file.Length); ctx.Response.OutputStream.Close(); ctx.Response.Close(); txtHttpLog.Text += "Response: 404 Not Found\r\n\r\n"; } } catch (Exception ex) { txtHttpLog.Text += "\r\nException: Server Stopped!!!\r\n\r\n"; // txtHttpLog.Text += "\r\nException: " + ex.Message + "\r\n\r\n"; break; } txtHttpLog.Select(0, 0); } }
static void Main(string[] args) { // Create a HTTP listener. HttpListener listener = new HttpListener(); listener.Prefixes.Add(MyEndpoint); listener.Start(); // will abort if port not permitted and not running in Administrator mode. try { ListenerLoop(listener); Console.Write(DateTime.UtcNow + ": Listening at"); foreach (string p in listener.Prefixes) Console.Write(" " + p); Console.WriteLine("\nPress any key to exit..."); Console.ReadKey(); } catch (Exception ex) { Console.WriteLine("Exception: Message:" + ex.Message); } finally { listener.Close(); } }
public void Start() { logger = LoggerFactory.GetLogger("SimpleHttpServer.Server"); logger.Info("Server starting on port {0}", port); if (listener != null) { logger.Fatal("Server already started"); throw new InvalidOperationException("Already started"); } listener = new HttpListener(); listener.Prefixes.Add(string.Format("http://*:{0}/", port)); try { listener.Start(); } catch(Exception ex) { logger.Fatal("Error starting server", ex); throw; } logger.Info("Server started"); logger.Debug("Waiting for first request"); listener.BeginGetContext(ProcessRequest, null); }
public async Task SendEmptyData_Success() { using (HttpListener listener = new HttpListener()) { listener.Prefixes.Add(ServerAddress); listener.Start(); Task<HttpListenerContext> serverAccept = listener.GetContextAsync(); WebSocketClient client = new WebSocketClient(); Task<WebSocket> clientConnect = client.ConnectAsync(new Uri(ClientAddress), CancellationToken.None); HttpListenerContext serverContext = await serverAccept; Assert.True(serverContext.Request.IsWebSocketRequest); HttpListenerWebSocketContext serverWebSocketContext = await serverContext.AcceptWebSocketAsync(null); WebSocket clientSocket = await clientConnect; byte[] orriginalData = new byte[0]; await clientSocket.SendAsync(new ArraySegment<byte>(orriginalData), WebSocketMessageType.Binary, true, CancellationToken.None); byte[] serverBuffer = new byte[orriginalData.Length]; WebSocketReceiveResult result = await serverWebSocketContext.WebSocket.ReceiveAsync(new ArraySegment<byte>(serverBuffer), CancellationToken.None); Assert.True(result.EndOfMessage); Assert.Equal(orriginalData.Length, result.Count); Assert.Equal(WebSocketMessageType.Binary, result.MessageType); Assert.Equal(orriginalData, serverBuffer); clientSocket.Dispose(); } }
public async void Start() { _listener.Prefixes.Add(_prefix); _listener.Start(); Console.WriteLine($"Started listening on {_prefix}"); while (_listener.IsListening) { try { var context = await _listener.GetContextAsync(); var stopwatch = new Stopwatch(); Console.WriteLine($"Request starting HTTP/{context.Request.ProtocolVersion} {context.Request.HttpMethod} {context.Request.Url}"); stopwatch.Start(); await ProcessRequest(context); stopwatch.Stop(); Console.WriteLine($"Request finished in {stopwatch.Elapsed.TotalMilliseconds:0.####}ms {context.Response.StatusCode} {context.Response.ContentType}"); } catch (Exception ex) { Console.WriteLine(ex.Message); } } }
public async Task Listen(string prefix, int maxConcurrentRequests, CancellationToken token) { HttpListener listener = new HttpListener(); try { listener.Prefixes.Add(prefix); listener.Start(); var requests = new HashSet<Task>(); for (int i = 0; i < maxConcurrentRequests; i++) requests.Add(listener.GetContextAsync()); while (!token.IsCancellationRequested) { Task t = await Task.WhenAny(requests); requests.Remove(t); if (t is Task<HttpListenerContext>) { var context = (t as Task<HttpListenerContext>).Result; requests.Add(ProcessRequestAsync(context)); requests.Add(listener.GetContextAsync()); } } } catch (Exception ex) { Console.WriteLine(ex); } }
public MyApi() { var httpListener = new System.Net.HttpListener(); httpListener.Prefixes.Add(MyEndPoint.Uri.ToString()); httpListener.Start(); }
public void Start() { listener = new HttpListener(); string virtualDirectory = Configuration.VirtualDirectory; if (virtualDirectory.EndsWith("/") == false) virtualDirectory = virtualDirectory + "/"; listener.Prefixes.Add("http://+:" + Configuration.Port + virtualDirectory); switch (Configuration.AnonymousUserAccessMode) { case AnonymousUserAccessMode.None: listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication; break; case AnonymousUserAccessMode.All: break; case AnonymousUserAccessMode.Get: listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication | AuthenticationSchemes.Anonymous; listener.AuthenticationSchemeSelectorDelegate = request => { return request.HttpMethod == "GET" || request.HttpMethod == "HEAD" ? AuthenticationSchemes.Anonymous : AuthenticationSchemes.IntegratedWindowsAuthentication; }; break; default: throw new ArgumentException("Cannot understand access mode: " + Configuration.AnonymousUserAccessMode ); } listener.Start(); listener.BeginGetContext(GetContext, null); }
public static async void ThreadProcAsync() { string uriPrefix = ConfigurationManager.AppSettings["ListenerPrefix"]; using (System.Net.HttpListener listener = new System.Net.HttpListener()) { listener.Prefixes.Add(uriPrefix); listener.IgnoreWriteExceptions = true; // For the sake of the development convenience, this code opens default web browser // with this server url when project is started in the debug mode as a console app. #if DEBUG if (!IsServiceMode) { System.Diagnostics.Process.Start(uriPrefix.Replace("+", "localhost"), null); } #endif listener.Start(); Console.WriteLine("Start listening on " + uriPrefix); Console.WriteLine("Press Control-C to stop listener..."); while (Listening) { HttpListenerContext context = await listener.GetContextAsync(); #pragma warning disable 4014 Task.Factory.StartNew(() => ProcessRequestAsync(listener, context)); #pragma warning restore 4014 } } }
public static void AssembyInitialize(TestContext testcontext) { listener = new HttpListener(); listener.Prefixes.Add("http://+:" + Port + WebSocketConstants.UriSuffix + "/"); listener.Start(); RunWebSocketServer().Fork(); }
public void BasicRoundTrip() { var serializer = new JsonCommonSerializer(); var server = new HttpListener(); server.Prefixes.Add("http://localhost:20000/"); server.Start(); var serverTransport = server.GenerateTransportSource(); var serverRouter = new DefaultMessageRouter(serverTransport, serializer); serverRouter.AddService<IMyService>(new MyService()); var client = new ClientWebSocket(); client.Options.SetBuffer(8192, 8192); var clientTransport = client.GenerateTransportSource(); var clientRouter = new DefaultMessageRouter(clientTransport, serializer); var proxy = clientRouter.AddInterface<IMyService>(); client.ConnectAsync(new Uri("ws://localhost:20000/"), CancellationToken.None).Wait(); var result = proxy.Add(3, 4).Result; Assert.Equal(7, result); clientRouter.Dispose(); clientTransport.Dispose(); client.Dispose(); serverRouter.Dispose(); serverTransport.Dispose(); server.Stop(); server.Close(); }
public void ShouldConfigure() { XmlConfigurator.Configure(); ILog logger = LogManager.GetLogger(typeof(HttpAppenderTests)); using (var listener = new HttpListener()) { listener.Prefixes.Add("http://localhost:34343/"); listener.AuthenticationSchemes = AuthenticationSchemes.Basic; listener.Start(); try { throw new Exception("KABOOM!"); } catch (Exception e) { logger.Error("Oh noes!", e); } var ctx = listener.GetContext(); using (var reader = new StreamReader(ctx.Request.InputStream)) { var body = reader.ReadToEnd(); Console.WriteLine(body); Assert.IsNotNull(body); HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)ctx.User.Identity; Assert.AreEqual("derp", identity.Name); Assert.AreEqual("darp", identity.Password); } ctx.Response.Close(); } }
public void Start() { Task.Run(() => { _httpListener = new HttpListener(); _httpListener.Prefixes.Add(@"http://localhost:" +_portNumber +"/"); _httpListener.Start(); Console.WriteLine("The Http Transport Service has started..."); while (!IsStopped) { // Wait for the incoming request. HttpListenerContext context = _httpListener.GetContext(); HttpListenerRequest request = context.Request; // Obtain a response object. HttpListenerResponse response = context.Response; // Process the POST request to update the Employee object. if (request.HttpMethod == "POST") { UpdateEmployee(request, response); } } }); }
static int SelectNextAvailablePort() { var usedPorts = new List<int>(); var r = new Random(); int newPort; while (true) { using (var mListener = new HttpListener()) { newPort = r.Next(49152, 65535); if (usedPorts.Contains(newPort)) { continue; } mListener.Prefixes.Add(string.Format("http://localhost:{0}/", newPort)); try { mListener.Start(); } catch { continue; } } usedPorts.Add(newPort); break; } return newPort; }
// initialize git repo as follow // > mkdir repository // > cd repository // > git init . // > git config receive.denyCurrentBranch ignore static void Main(string[] args) { if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.Unix) { GitExe = "/usr/bin/git"; } try { RepositoryPath = args[0]; var port = Int32.Parse(args[1]); string prefix = String.Format("http://localhost:{0}/", port); var listener = new HttpListener(); listener.Prefixes.Add(prefix); listener.Start(); Console.WriteLine("Listening at " + prefix); while (true) { // simple handle one request at a time ProcessRequest(listener.GetContext()); } } catch (Exception ex) { Console.WriteLine(ex); } }
static void Main(string[] args) { try { dbaddr = db.confreader.getservers(true); listener = new HttpListener(); listener.Prefixes.Add("http://*:" + port + "/"); listener.Start(); listen = new Thread(ListenerCallback); listen.Start(); for (var i = 0; i < workers.Length; i++) { workers[i] = new Thread(Worker); workers[i].Start(); } Console.CancelKeyPress += (sender, e) => { Console.WriteLine("Terminating..."); listener.Stop(); while (contextQueue.Count > 0) Thread.Sleep(100); Environment.Exit(0); }; Console.WriteLine("Listening at port " + port + "..."); Thread.CurrentThread.Join(); } catch (Exception ex) { Console.WriteLine("Error: " + ex.ToString()); Console.ReadLine(); } }
public void Start() { _httpListener = new System.Net.HttpListener(); _httpListener.Prefixes.Add($"http://+:{_port}/"); _httpListener.Start(); }
/// <exclude /> public override void Open() { mHttpListener = new System.Net.HttpListener(); mHttpListener.Prefixes.Add(mUrl); mHttpListener.Start(); Task.Run(ListenAsync); }
public static void Main(string[] args) { var port = args.Length == 1 ? int.Parse(args [0]) : 8001; var listener = new System.Net.HttpListener(); // for Non Admin rights // netsh http add urlacl url=http://*:8001/api/Effect user=DOMAIN/user listener.Prefixes.Add(string.Format("http://*:{0}/api/Effect/", port)); listener.Start(); ThreadPool.QueueUserWorkItem((o) => { try { Console.WriteLine("Webserver running..."); while (listener.IsListening) { ThreadPool.QueueUserWorkItem((c) => { var ctx = c as HttpListenerContext; try { var contentLength = (int)ctx.Request.ContentLength64; var buffer = new byte[contentLength]; ctx.Request.InputStream.Read(buffer, 0, contentLength); var obj = Encoding.ASCII.GetString(buffer); var d = (Data)JsonConvert.DeserializeObject(obj, typeof(Data)); string error = String.Empty; byte[] buf = RunMGCB(d.Code, d.Platform, out error); var result = JsonConvert.SerializeObject(new Result() { Compiled = buf, Error = error }); ctx.Response.ContentLength64 = result.Length; ctx.Response.OutputStream.Write(Encoding.UTF8.GetBytes(result), 0, result.Length); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } // suppress any exceptions finally { // always close the stream ctx.Response.OutputStream.Close(); } }, listener.GetContext()); } } catch { } }); Console.Read(); listener.Stop(); listener.Close(); }
/// <summary> /// Starts the listener and request processing threads. /// </summary> internal void Start(System.Net.HttpListener listener, AppFunc appFunc, IList <IDictionary <string, object> > addresses, IDictionary <string, object> capabilities, LoggerFactoryFunc loggerFactory) { Contract.Assert(_appFunc == null); // Start should only be called once Contract.Assert(listener != null); Contract.Assert(appFunc != null); Contract.Assert(addresses != null); _listener = listener; _appFunc = appFunc; _loggerFactory = loggerFactory; if (_loggerFactory != null) { _logger = _loggerFactory(typeof(OwinHttpListener).FullName); } _basePaths = new List <string>(); foreach (var address in addresses) { // build url from parts string scheme = address.Get <string>("scheme") ?? Uri.UriSchemeHttp; string host = address.Get <string>("host") ?? "localhost"; string port = address.Get <string>("port") ?? "5000"; string path = address.Get <string>("path") ?? string.Empty; // if port is present, add delimiter to value before concatenation if (!string.IsNullOrWhiteSpace(port)) { port = ":" + port; } // Assume http(s)://+:9090/BasePath/, including the first path slash. May be empty. Must end with a slash. if (!path.EndsWith("/", StringComparison.Ordinal)) { // Http.Sys requires that the URL end in a slash path += "/"; } _basePaths.Add(path); // add a server for each url string url = scheme + "://" + host + port + path; _listener.Prefixes.Add(url); } _capabilities = capabilities; _disconnectHandler = new DisconnectHandler(_listener); if (!_listener.IsListening) { _listener.Start(); _disconnectHandler.Initialize(); } OffloadStartNextRequest(); }
public void StartListening() { CheckNotDisposed(); using (new ContextScope(new AmbientContext())) { Start(this, EventArgs.Empty); } _listener.Start(); Task.Run(AcceptRequests); }
public void Start(string uriPrefix, Action <HttpListenerContext> sessionReceived) { _httpServer = new System.Net.HttpListener(); _httpServer.Prefixes.Add(uriPrefix); _httpServer.Start(); _running = true; _httpServer.BeginGetContext(HandleRequest, new SessionState(this, sessionReceived)); }
public void StartListening() { CheckNotDisposed(); using (new ContextScope(new AmbientContext())) { Start(this, EventArgs.Empty); } _listener.Start(); QueueNextRequestPending(); }
/// <summary> /// Start the http listener. /// </summary> public async void Start() { // If not running. if (!_running) { try { // Create a new http listener if (_listener == null) { _listener = new System.Net.HttpListener(); // Add URI prefixes to listen for. foreach (string uri in _uriList) { _listener.Prefixes.Add(uri); } } // Set the Authentication Schemes. _listener.AuthenticationSchemes = _authenticationSchemes; if (_authenticationSchemeSelectorDelegate != null) { _listener.AuthenticationSchemeSelectorDelegate = _authenticationSchemeSelectorDelegate; } // Start the listener _listener.Start(); _running = true; // Keep the service in the running start // listen for in-comming requests. while (_running) { // Wait for the next request. HttpListenerContext listenerContext = await _listener.GetContextAsync(); // Send the http context to the handler. if (listenerContext != null) { AsynchronousListener(listenerContext); } } } catch (Exception) { if (_listener != null) { _listener.Close(); } throw; } } }
protected void Start(IEnumerable <string> urlBases, WaitCallback listenCallback) { // *** Already running - just leave it in place if (this.IsStarted) { return; } if (this.Listener == null) { Listener = CreateHttpListener(); } foreach (var urlBase in urlBases) { if (HostContext.Config.HandlerFactoryPath == null) { HostContext.Config.HandlerFactoryPath = ListenerRequest.GetHandlerPathIfAny(urlBase); } Listener.Prefixes.Add(urlBase); } try { Listener.Start(); IsStarted = true; } catch (HttpListenerException ex) { if (Config.AllowAclUrlReservation && ex.ErrorCode == 5 && registeredReservedUrl == null) { foreach (var urlBase in urlBases) { registeredReservedUrl = AddUrlReservationToAcl(urlBase); if (registeredReservedUrl == null) { break; } } if (registeredReservedUrl != null) { Listener = null; Start(urlBases, listenCallback); return; } } throw ex; } ThreadPool.QueueUserWorkItem(listenCallback); }
public virtual void Start() { try { _listener = new System.Net.HttpListener(); _listener.Prefixes.Add(string.Format("http://+:{0}/{1}", Port, Prefix)); _listener.Start(); _listener.BeginGetContext(this.Listener_Request, _listener); } catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; } }
/// <summary> /// Starts listening for incoming connections /// </summary> public override void Start() { if (Running) { return; } listener = new System.Net.HttpListener(); listener.Prefixes.Add(prefix); listener.Start(); listener.BeginGetContext(EndGetRequest, listener); }
private static void Main(string[] args) { // Use the Log4NET adapter for logging LoggerFactory.Factory = new Log4NetAdapter(); // Obtain the HTTP binding settings var webdavProtocol = ConfigurationManager.AppSettings["webdav.protocol"] ?? "http"; var webdavIp = ConfigurationManager.AppSettings["webdav.ip"] ?? "127.0.0.1"; var webdavPort = ConfigurationManager.AppSettings["webdav.port"] ?? "11111"; using (var httpListener = new System.Net.HttpListener()) { // Add the prefix httpListener.Prefixes.Add($"{webdavProtocol}://{webdavIp}:{webdavPort}/"); // Use basic authentication if requested var webdavUseAuthentication = XmlConvert.ToBoolean(ConfigurationManager.AppSettings["webdav-authentication"] ?? "false"); if (webdavUseAuthentication) { // Check if HTTPS is enabled if (webdavProtocol != "https" && s_log.IsWarnEnabled) { s_log.Warn("Most WebDAV clients cannot use authentication on a non-HTTPS connection"); } // Set the authentication scheme and realm httpListener.AuthenticationSchemes = AuthenticationSchemes.Basic; httpListener.Realm = "WebDAV server"; } else { // Allow anonymous access httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous; } // Start the HTTP listener httpListener.Start(); // Start dispatching requests var cancellationTokenSource = new CancellationTokenSource(); DispatchHttpRequestsAsync(httpListener, cancellationTokenSource.Token); // Wait until somebody presses return Console.WriteLine("WebDAV server running. Press 'x' to quit."); while (Console.ReadKey().KeyChar != 'x') { ; } cancellationTokenSource.Cancel(); } }
/// <summary> /// Will create the web server on the specified port. If the port is in use /// a random port number will automatically be used. Callers should always /// verify the port with the BaseUri property. /// </summary> /// <param name="possibleRequests">The relative Uri's this server will handle.</param> /// <param name="port">The port to listen on.</param> public WebServer(Uri[] possibleRequests, int port) { if (possibleRequests == null) { throw new ArgumentNullException("possibleRequests"); } foreach (Uri possible in possibleRequests) { if (possible.IsAbsoluteUri) { throw new ArgumentOutOfRangeException("possibleRequests", "Uris provided must be relative."); } } if ((port < 0) || (port > _maxPort)) { throw new ArgumentOutOfRangeException("port", string.Format("Value must be between 0 and {0}", _maxPort)); } _possibleRequests = possibleRequests; bool foundValidPort = false; while (!foundValidPort) { _baseUri = new Uri(string.Format("{0}://{1}:{2}/Test/", Uri.UriSchemeHttp, _serverIpAddress, port)); _listener = new System.Net.HttpListener(); _listener.Prefixes.Add(_baseUri.OriginalString); try { // triggers port usage and validation _listener.Start(); _listener.Stop(); foundValidPort = true; } catch (HttpListenerException hle) { if (hle.ErrorCode == 32) // Magic Number: PortInUse Error { // generate random port port = new Random().Next(_minRandomPort, _maxPort); } else { throw hle; } } } }
static void Main(string[] args) { Threads(); System.Net.HttpListener listener = new System.Net.HttpListener(); // This doesn't seem to ignore all write exceptions, so in WriteResponse(), we still have a catch block. listener.IgnoreWriteExceptions = true; listener.Prefixes.Add("http://*:8080/"); try { listener.Start(); // Increase the HTTP.SYS backlog queue from the default of 1000 to 65535. // To verify that this works, run `netsh http show servicestate`. Network.Utils.HttpApi.SetRequestQueueLength(listener, 65535); for (;;) { HttpListenerContext context = null; try { context = listener.GetContext(); ThreadPool.QueueUserWorkItem(new WaitCallback(RequestCallback), context); context = null; // ownership has been transferred to RequestCallback } catch (HttpListenerException ex) { Console.WriteLine(ex.Message); } finally { if (context != null) { context.Response.Close(); } } } } catch (HttpListenerException ex) { Console.WriteLine(ex.Message); } finally { // Stop listening for requests. listener.Close(); Console.WriteLine("Done Listening."); } }
public void Start() { if (IsRunning) { return; } listener = new HttpListener(); //prefixes.Add("http://127.0.0.1:8000/"); //prefixes.Add("http://192.168.7.245:8000/"); foreach (string prefix in prefixes) { listener.Prefixes.Add(prefix); } listener.Start(); listener.BeginGetContext(EndGetRequest, listener); }
static void Main(string[] args) { try { // 判斷作業系統是否支援 if (!System.Net.HttpListener.IsSupported) { Console.WriteLine("作業系統不支援HttpListener類別"); return; } // 取得本機的識別名稱 string hostname = Dns.GetHostName(); // 取得主機的DNS資訊 IPAddress serverIP = Dns.Resolve(hostname).AddressList[0]; // HTTP Server Port = 80 string Port = "80"; string prefix = "http://" + serverIP.ToString() + ":" + Port + "/"; Console.WriteLine("HTTP server started at: " + prefix); System.Net.HttpListener httpListener = new System.Net.HttpListener(); // 設定Prefixes屬性,以指定HTTP伺服端的IP位址及通訊埠 httpListener.Prefixes.Add(prefix); // 等候自用戶端的連線請求 httpListener.Start(); //Console.WriteLine("HTTP server started at: " + Dns.GetHostName() + ":" + Port); HTTPSession httpSession = new HTTPSession(httpListener); // 執行緒 ThreadStart serverThreadStart = new ThreadStart(httpSession.HTTPSessionThread); Thread serverthread = new Thread(serverThreadStart); serverthread.Start(); } catch (Exception ex) { Console.WriteLine(ex.StackTrace.ToString()); } }
static void Main(string[] args) { Threads(); System.Net.HttpListener listener = new System.Net.HttpListener(); // This doesn't seem to ignore all write exceptions, so in WriteResponse(), we still have a catch block. listener.IgnoreWriteExceptions = true; listener.Prefixes.Add("http://*:8080/"); try { listener.Start(); for (;;) { HttpListenerContext context = null; try { context = listener.GetContext(); ThreadPool.QueueUserWorkItem(new WaitCallback(RequestCallback), context); context = null; // ownership has been transferred to RequestCallback } catch (HttpListenerException ex) { Console.WriteLine(ex.Message); } finally { if (context != null) { context.Response.Close(); } } } } catch (HttpListenerException ex) { Console.WriteLine(ex.Message); } finally { // Stop listening for requests. listener.Close(); Console.WriteLine("Done Listening."); } }
public WebServer( ) { Database = DBNS.Database.GetDatabase(@"C:\Databasefiles\Test\"); if (Database.IsNew) { Init.Go(Database); // Creates initial tables, stored procedures etc. } listener = new System.Net.HttpListener( ); // listener.Prefixes.Add( "http://localhost:8080/" ); // Note: to listen to internet addresses, program will need to run with admin privilege // Or configuration will be needed. e.g. run CMD as Administrator, then type: // netsh http add urlacl url=http://+:8080/ user=GEORGE-DELL\pc listener.Prefixes.Add("http://+:8080/"); listener.Start( ); }
public async Task Start() { _cts = new CancellationTokenSource(); _httpListener = new System.Net.HttpListener(); _httpListener.Prefixes.Add("http://localhost:8181/incoming/"); _httpListener.Start(); Console.WriteLine("Listening at {0}", _httpListener.Prefixes.First()); while (!_cts.IsCancellationRequested) { var context = await _httpListener.GetContextAsync(); var handlerTask = HandleNewConnection(context); _listeners.TryAdd(handlerTask); #pragma warning disable 4014 handlerTask.ContinueWith(t => _listeners.TryRemove(handlerTask)); #pragma warning restore 4014 } }
private void Listen() { _listener = new System.Net.HttpListener(); _listener.Prefixes.Add("http://*:" + _port.ToString() + "/"); _listener.Start(); while (true) { try { System.Net.HttpListenerContext context = _listener.GetContext(); Process(context); } catch (Exception ex) { } } }
public async Task Listen(ushort port) { try { using (System.Net.HttpListener listener = new System.Net.HttpListener()) { listener.Prefixes.Add($"http://localhost:{port.ToString()}/Device/Data/"); listener.Start(); Console.WriteLine("开始监听"); while (true) { try { HttpListenerContext context = await listener.GetContextAsync();//阻塞 HttpListenerRequest request = context.Request; string postData = new StreamReader(request.InputStream).ReadToEnd(); Console.WriteLine("收到请求:" + postData); HttpListenerResponse response = context.Response;//响应 string responseBody = "OK"; response.ContentLength64 = System.Text.Encoding.UTF8.GetByteCount(responseBody); response.StatusCode = 200; //输出响应内容 Stream output = response.OutputStream; using (StreamWriter sw = new StreamWriter(output)) { sw.Write(responseBody); } Console.WriteLine("响应结束"); } catch (Exception err) { Console.WriteLine(err.Message); } } } } catch (Exception err) { Console.WriteLine("程序异常,请重新打开程序:" + err.Message); } }
public void Listen() { if (!HttpListener.IsSupported) { throw new System.InvalidOperationException( "使用 HttpListener 必须为 Windows XP SP2 或 Server 2003 以上系统!"); } string[] prefixes = new string[] { host }; listener = new HttpListener(); foreach (string s in prefixes) { listener.Prefixes.Add(s); } listener.Start(); while (is_active) { HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; Console.WriteLine("{0} {1} HTTP/1.1", request.HttpMethod, request.RawUrl); Console.WriteLine("User-Agent: {0}", request.UserAgent); Console.WriteLine("Accept-Encoding: {0}", request.Headers["Accept-Encoding"]); Console.WriteLine("Connection: {0}", request.KeepAlive ? "Keep-Alive" : "close"); Console.WriteLine("Host: {0}", request.UserHostName); HttpListenerResponse response = context.Response; if (request.HttpMethod == "GET") { OnGetRequest(request, response); } else { OnPostRequest(request, response); } } }
private static void Main() { var listener = new HttpListener(); const string host = "http://192.168.1.42:9001/"; listener.Prefixes.Add(host); listener.Start(); Console.WriteLine("Listening on {0}...", host); new Thread(() => { Console.ReadLine(); Environment.Exit(0); }).Start(); while (true) { var context = listener.GetContext(); var response = context.Response; var request = context.Request; var query = request.QueryString["q"]; Console.WriteLine("{0} - {1}", DateTime.Now, query); var res = ""; if (query != null) { if (Regex.IsMatch(query, "Share")) res = "Point"; } var buffer = Encoding.UTF8.GetBytes(res); response.ContentLength64 = buffer.Length; var output = response.OutputStream; output.Write(buffer, 0, buffer.Length); output.Close(); } }