static void Main() { Console.Title = "Samples.CustomChecks.3rdPartySystem"; Console.WriteLine("Press enter key to toggle the server to return a error or success"); Console.WriteLine("Press any key to exit"); using (listener = new HttpListener()) { listener.Prefixes.Add("http://localhost:57789/"); listener.Start(); listener.BeginGetContext(ListenerCallback, listener); while (true) { ConsoleKeyInfo key = Console.ReadKey(); Console.WriteLine(); if (key.Key != ConsoleKey.Enter) { return; } listener.Close(); if (isReturningOk) { Console.WriteLine("\r\nCurrently returning success"); } else { Console.WriteLine("\r\nCurrently returning error"); } isReturningOk = !isReturningOk; } } }
public void FixtureSetup() { _listener = new HttpListener(_uri.OriginalString); _listener.Start(); _server = new Tracker(); _server.RegisterListener(_listener); _listener.Start(); }
static void StartListener() { listener = new HttpListener(); listener.Prefixes.Add("http://localhost:57789/"); listener.Start(); listener.BeginGetContext(ListenerCallback, listener); }
void Awake() { listener = new HttpListener(); listener.Prefixes.Add("http://*:7663/"); listener.Start(); listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener); }
public Listener () { EndPoints = new List<IPEndPoint> (); listener = new HttpListener (); listener.Prefixes.Add (KeepAliveTest.URL); listener.Start (); listener.BeginGetContext (Handle, null); }
public Task Start(string binFile, Action <double> progress) { IsCanceled = false; listener?.Start(); return(Task.Run(async() => { var context = listener?.GetContext(); context.Response.SendChunked = false; context.Response.ContentType = System.Net.Mime.MediaTypeNames.Application.Octet; context.Response.AddHeader("Content-disposition", "attachment; filename=" + Path.GetFileName(binFile)); using (var stream = context.Response.OutputStream) { using (FileStream fs = File.OpenRead(binFile)) { context.Response.ContentLength64 = fs.Length; byte[] buffer = new byte[64 * 1024]; int read; int readed = 0; using (BinaryWriter bw = new BinaryWriter(stream)) { try { while ((read = fs.Read(buffer, 0, buffer.Length)) > 0) { if (!IsCanceled) { bw.Write(buffer, 0, read); bw.Flush(); //seems to have no effect readed += read; progress(100.0 * readed / fs.Length); } } bw.Close(); } catch (Exception ex) { } } } await Task.Delay(500);// wait for ESP to write to SPI if (!IsCanceled) { context.Response.StatusCode = (int)HttpStatusCode.OK; context.Response.StatusDescription = "OK"; } else { context.Response.StatusCode = (int)HttpStatusCode.NotAcceptable; context.Response.StatusDescription = "Canceled"; } stream.Close(); } })); }
public NetEventHandler() { BaseUrl = Net.GetUrl(Net.GetIp(IPType.All), Net.FindPort(), "").ToString(); ServicePointManager.DefaultConnectionLimit = 100; _httpListener = new HttpListener(); _httpListener.Prefixes.Add(BaseUrl); _httpListener.Start(); ThreadPool.QueueUserWorkItem(Listen); }
public HttpListener CreateListener(List<string> addresses) { var listener = new HttpListener(); addresses.ForEach(a => listener.Prefixes.Add(a)); listener.Start(); return listener; }
public void StartListener (Object args) { HttpListener listener = new HttpListener (); string prefix = string.Format ("http://*:8880/{0}/", args); listener.Prefixes.Add (prefix); listener.Start (); for (; ; ) { HttpListenerContext ctx = listener.GetContext (); new Thread (new Worker (ctx).ProcessRequest).Start (); } }
static void Main () { HttpListener listener = new HttpListener (); listener.IgnoreWriteExceptions = true; listener.Prefixes.Add ("http://*:8081/"); listener.Start (); listener.BeginGetContext (RequestHandler, listener); while (true) { Thread.Sleep (250); if (File.Exists ("stop-server.tmp")) break; } listener.Close (); File.Create ("finish-server.tmp").Close (); }
private static void Listen () { HttpListener listener = new HttpListener (); listener.Prefixes.Add ("http://127.0.0.1:8080/a/"); listener.Start (); HttpListenerResponse response = listener.GetContext().Response; response.ContentType = "text/xml"; byte [] buffer = Encoding.UTF8.GetBytes ("<ok/>"); response.ContentLength64 = buffer.Length; Stream output = response.OutputStream; output.Write (buffer, 0, buffer.Length); output.Close (); listener.Stop (); }
static int Main () { TinyHost h = CreateHost (); HttpListener listener = new HttpListener (); listener.Prefixes.Add ("http://" + IPAddress.Loopback.ToString () + ":8081/"); listener.Start (); HttpListenerContext ctx = listener.GetContext (); StreamWriter sw = new StreamWriter (ctx.Response.OutputStream); h.Execute ("FaultService.asmx", sw); sw.Flush (); ctx.Response.Close (); return 0; }
static void Main(string[] args) { Console.WriteLine("Started"); HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://localhost:8888/decorator/"); listener.Start(); while (true) { HttpListenerContext ctx = listener.GetContext(); Console.WriteLine("connected"); ProcessRequest(ctx); } }
static int Main () { HttpListener listener = new HttpListener (); listener.Prefixes.Add ("http://" + IPAddress.Loopback.ToString () + ":8001/"); listener.Start (); IAsyncResult result = listener.BeginGetContext (new AsyncCallback (ListenerCallback), listener); HttpWebRequest request = (HttpWebRequest) WebRequest.Create ("http://" + IPAddress.Loopback.ToString () + ":8001/?a=1&b=2"); request.Accept = "image/png,text/html"; request.Method = "GET"; HttpWebResponse response = (HttpWebResponse) request.GetResponse (); response.Close (); result.AsyncWaitHandle.WaitOne (); return exitCode; }
static void Main(string[] args) { var port = "1982"; var root = "."; var prefix = String.Format("http://*:{0}/", port); Log("listening {0}", prefix); var listener = new HttpListener(); listener.Prefixes.Add(prefix); listener.Start(); while (true) { var context = listener.GetContext(); var request = context.Request; var response = context.Response; Log("{0} {1}", request.HttpMethod, request.RawUrl); if (request.RawUrl == "/api") { ApiResponse(response, request); } else { var path = root + request.RawUrl; try { var content = File.ReadAllBytes(path); response.ContentType = "text/plain"; response.AppendHeader("Content-Length", content.Length.ToString()); response.OutputStream.Write(content, 0, content.Length); } catch (FileNotFoundException e) { ErrorResponse(response, 404, e); } catch (UnauthorizedAccessException e) { ErrorResponse(response, 403, e); } catch (Exception e) { ErrorResponse(response, 500, e); } } Log(" -> {0}", response.StatusCode); response.Close(); } }
static void run_server () { HttpListener listener = new HttpListener (); listener.Prefixes.Add (url); listener.Start (); while (server_count < count) { HttpListenerContext context = listener.GetContext (); HttpListenerResponse response = context.Response; string responseString = "my data"; byte [] buffer = Encoding.UTF8.GetBytes (responseString); response.ContentLength64 = buffer.Length; Stream output = response.OutputStream; output.Write (buffer, 0, buffer.Length); output.Close (); server_count++; } }
public void Start(int port) { if (listener != null && listener.IsListening) { return; } System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = "cmd.exe"; startInfo.Arguments = "netsh http add urlacl url=http://+:" + port.ToString() + "/ user="******"\\" + Environment.UserName; process.StartInfo = startInfo; process.Start(); listener = new HttpListener(); //listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous; try { //listener.Prefixes.Add("http://localhost:" + port.ToString() + "/"); listener.Prefixes.Add("http://*:" + port.ToString() + "/"); //listener.Prefixes.Add("http://ip:2006/test/"); //hl.Prefixes.Add("http://*:7867/test/"); listener.Start(); //Console.ReadKey(); } catch (Exception e) { //Console.WriteLine("Error!!!!!!!!!!!!!!"); Console.ReadKey(); throw e; } //Console.WriteLine("Started!!!!!!!!!!!!!!!!"); //Console.ReadKey(); running = true; Thread thread = new Thread(new ThreadStart(listen)); thread.Start(); }
static void Main () { string location = string.Format ("http://{0}:{1}/", IPAddress.Loopback.ToString (), 8081); HttpListener listener = new HttpListener (); listener.Prefixes.Add (location); listener.Start (); listener.BeginGetContext (new AsyncCallback (ListenerCallback), listener); WebRequest webRequest = WebRequest.Create ("http://localhost:8081"); IAsyncResult requestResult = webRequest.BeginGetResponse ( null, null); try { webRequest.EndGetResponse (requestResult); Assert.Fail ("#A1"); } catch (WebException ex) { Assert.AreEqual (typeof (WebException), ex.GetType (), "#A2"); Assert.IsNull (ex.InnerException, "#A3"); Assert.AreEqual (WebExceptionStatus.ProtocolError, ex.Status, "#A4"); Assert.IsFalse (_calledBack, "#A5"); HttpWebResponse response = ex.Response as HttpWebResponse; Assert.IsNotNull (response, "#A6"); using (StreamReader sr = new StreamReader (response.GetResponseStream ())) { string body = sr.ReadToEnd (); Assert.IsTrue (body.IndexOf ("<h1>Bad Request") != -1, "#A7"); } Assert.AreEqual (HttpStatusCode.BadRequest, response.StatusCode, "#A8"); } webRequest = WebRequest.Create (location); requestResult = webRequest.BeginGetResponse (null, null); HttpWebResponse webResponse = (HttpWebResponse) webRequest. EndGetResponse (requestResult); using (StreamReader sr = new StreamReader (webResponse.GetResponseStream ())) { string body = sr.ReadToEnd (); Assert.AreEqual ("<HTML><BODY> Hello world!</BODY></HTML>", body, "#B1"); } Assert.AreEqual (HttpStatusCode.OK, webResponse.StatusCode, "#B2"); Assert.IsTrue (_calledBack, "#B3"); }
static void Main(string[] args) { listener = new HttpListener(); listener.Prefixes.Add("http://localhost:3270/"); listener.Start(); Thread listenerThread = new Thread(new ThreadStart(ProcessSokectListener)); listenerThread.Start(); DateTime timeNow = DateTime.UtcNow; while (true) { TimeSpan timeSpan = DateTime.UtcNow - timeNow; if (timeSpan.Seconds >= 1) { timeNow = DateTime.UtcNow; Console.WriteLine("Main Thread : " + timeNow); } } }
static UrlPrefix() { // Find a URL prefix that is not in use on this machine *and* uses a port that's not in use. // Once we find this prefix, keep a listener on it for the duration of the process, so other processes // can't steal it. Guid processGuid = Guid.NewGuid(); for (int port = 1024; port <= IPEndPoint.MaxPort; port++) { string prefix = $"http://localhost:{port}/{processGuid:N}/"; var listener = new HttpListener(); try { listener.Prefixes.Add(prefix); listener.Start(); s_processPrefixListener = listener; s_processPrefix = prefix; break; } catch (Exception e) { // can't use this prefix listener.Close(); // Remember the exception for later s_processPrefixException = e; // If this is not an HttpListenerException, something very wrong has happened, and there's no point // in trying again. if (!(e is HttpListenerException)) break; } } // At this point, either we've reserved a prefix, or we've tried everything and failed. If we failed, // we've saved the exception for later. We'll defer actually *throwing* the exception until a test // asks for the prefix, because dealing with a type initialization exception is not nice in xunit. }
static void Main () { string url = "http://localhost:6372/"; HttpListener listener = new HttpListener (); listener.Prefixes.Add (url); listener.Start (); listener.BeginGetContext (new AsyncCallback (ListenerCallback), listener); Stopwatch stopwatch = new Stopwatch (); stopwatch.Start (); Client client = Client.CreateInNewAppDomain (); client.Bombard (url, 10000, 20); Program p = new Program (); p.handle = new AutoResetEvent (false); client.Completed += p.CompletedHandler; if (!p.handle.WaitOne (30000, false)) throw new Exception ("Operation timed out"); Assert.AreEqual (10000, client.total, "#1"); Assert.IsTrue (stopwatch.Elapsed.TotalMilliseconds < 10000, "#2:" + stopwatch.Elapsed.TotalMilliseconds); }
public RemotingHttpListener (IPAddress addr, int port, HttpServerTransportSink sink) { this.sink = sink; bool find_port = false; if (port == 0) find_port = true; string address = null; if (addr == IPAddress.Any) address = "*"; #if NET_2_0 else if (addr == IPAddress.IPv6Any) address = "*"; #endif else address = addr.ToString (); listener = new HttpListener (); while (true) { Random rnd = null; if (find_port) { if (rnd == null) rnd = new Random (); port = rnd.Next (1025, 65000); } try { listener.Prefixes.Add (String.Format ("http://{0}:{1}/", address, port)); listener.Start (); local_port = port; break; } catch (Exception e) { if (!find_port) throw; listener.Prefixes.Clear (); // Port already in use } } listener.BeginGetContext (new AsyncCallback (OnGetContext), null); }
static void Main () { HttpListener listener = new HttpListener (); listener.Prefixes.Add ("http://*:8081/"); listener.Start (); HttpListenerContext context = listener.GetContext (); // Create the response. HttpListenerResponse response = context.Response; string responseString = "<html><body>hi client</body></html>"; byte [] buffer = Encoding.UTF8.GetBytes (responseString); response.ContentLength64 = buffer.Length; System.Threading.Thread.Sleep (3000); response.OutputStream.Write (buffer, 0, buffer.Length); if (response != null) response.Close (); listener.Close (); string dir = AppDomain.CurrentDomain.BaseDirectory; File.Create (Path.Combine (dir, "ok")).Close (); }
private void Start(CancellationToken token) { _listener?.Start(); do { try { HttpListenerContext?request = _listener?.GetContext(); if (token.IsCancellationRequested) { break; } ThreadPool.QueueUserWorkItem(ProcessRequest, request); } catch (HttpListenerException lex) { _log.Warning(lex); } catch (InvalidOperationException iex) { _log.Warning(iex); } }while (!token.IsCancellationRequested); }
//用户可能需要具有管理员身份才能运行此应用程序 static void Main() { var listener = new HttpListener(); listener.Prefixes.Add("http://+:8086/csharpfeeds/"); listener.Start(); // 打开指向将为其提供服务的源的浏览器。 string uri = @"http://localhost:8086/csharpfeeds/"; System.Diagnostics.Process browser = new System.Diagnostics.Process(); browser.StartInfo.FileName = "iexplore.exe"; browser.StartInfo.Arguments = uri; browser.Start(); // 为请求提供服务。 while (true) { var context = listener.GetContext(); var body = GetReplyBody(); context.Response.ContentType = "text/xml"; using (XmlWriter writer = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8)) body.WriteTo(writer); } }
public static async Task SimpleRequest_Succeeds() { string url = UrlPrefix.CreateLocal(); const string expectedResponse = "hello from HttpListener"; using (HttpListener listener = new HttpListener()) { listener.Prefixes.Add(url); listener.Start(); var serverContextTask = listener.GetContextAsync(); using (HttpClient client = new HttpClient()) { var clientTask = client.GetStringAsync(url); var serverContext = await serverContextTask; using (var response = serverContext.Response) { var responseBuffer = Encoding.UTF8.GetBytes(expectedResponse); response.ContentLength64 = responseBuffer.Length; using (var output = response.OutputStream) { await output.WriteAsync(responseBuffer, 0, responseBuffer.Length); } } var clientString = await clientTask; Assert.Equal(expectedResponse, clientString); } listener.Stop(); } }
static void Main(string[] args) { string[] lines = Properties.Resources.GRE.Split('\n'); string Headers = "<html><head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF8\">\n<title>GRE词汇表</title>\n</head>\n<body>\n"; string Enders = "</body></html>"; Random ran = new Random(); int beginLine = 0, endLine = 0; for (int i = 0; i < lines.Length; i++) { if (lines[i].Contains("<body>")) { beginLine = i + 1; } if (lines[i].Contains("</body>")) { endLine = i - 1; } } if (!HttpListener.IsSupported) { Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class."); return; } // Create a listener. HttpListener listener = new HttpListener(); // Add the prefixes. listener.Prefixes.Add("http://10.10.10.10:41519/"); listener.Start(); Console.WriteLine("Listening..."); while (true) { // Note: The GetContext method blocks while waiting for a request. HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; bool isReadyToQuit = false; string responseString = "<!DOCTYPE html PUBLIC \"-//WAPFORUM//DTD XHTML Mobile 1.0//EN\" \"http://www.wapforum.org/DTD/xhtml-mobile10.dtd\">\r\n <HTML><BODY> Hello world!</BODY></HTML>"; if (request.RawUrl.ToLower() == @"/quit") { responseString = "<HTML><BODY> Bye!</BODY></HTML>"; isReadyToQuit = true; } else { responseString = Headers; //string[] readyToShow = new string[100]; for (int i = 0; i < 100; i++) { string curLine = lines[ran.Next(beginLine, endLine)]; while (curLine == "") { curLine = lines[ran.Next(beginLine, endLine)]; } //readyToShow[i] = curLine; responseString += curLine + "\r\n"; } responseString += Enders; } // Obtain a response object. HttpListenerResponse response = context.Response; // Construct a response. Console.WriteLine(request.RawUrl); 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); // You must close the output stream. output.Close(); if (isReadyToQuit) { System.Threading.Thread.Sleep(1000); break; } } Console.WriteLine("quited."); listener.Stop(); }
public Task StartAsync(CancellationToken cancellationToken) { if (!HttpListener.IsSupported) { Logger.LogWarning("Windows XP SP2 or Server 2003 is required to use the HttpListener class."); return(Task.CompletedTask); } listener = new HttpListener(); listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous; try { listener.Prefixes.Add($"http://*:{Configuration.WebApiPort}/"); listener.Start(); } catch (System.Net.HttpListenerException ex) { Logger.LogWarning(ex, $"{ex.Message}:使用cmd命令[netsh http add urlacl url=http://*:{Configuration.WebApiPort}/ user=Everyone]"); } Logger.LogInformation($"JT808 Http Server start at {IPAddress.Any}:{Configuration.WebApiPort}."); Task.Run(async() => { while (listener.IsListening) { var context = await listener.GetContextAsync(); try { if (context.Request.RawUrl.StartsWith("/favicon.ico")) { context.Http404(); continue; } // 增加CORS // https://stackoverflow.com/questions/25437405/cors-access-for-httplistener context.Response.AppendHeader("Access-Control-Allow-Origin", "*"); if (context.Request.HttpMethod == HttpMethod.Options.Method) { context.Response.AddHeader("Access-Control-Allow-Headers", "*"); context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST"); context.Response.AddHeader("Access-Control-Max-Age", "1728000"); context.Http204(); } if (authorization.Authorization(context, out var principal)) { await ProcessRequestAsync(context, principal); } else { await context.Http401(); } } catch (AggregateException ex) { await context.Http500(); Logger.LogError(ex, ex.StackTrace); } catch (Exception ex) { await context.Http500(); Logger.LogError(ex, ex.StackTrace); } } }, cancellationToken); return(Task.CompletedTask); }
private static async Task <Token> RequestToken(ClientIdentifier clientIdentifier) { // prepare listen server for receiving token data if (!HttpListener.IsSupported || clientIdentifier == null) { return(null); } int listenPort = FindListenPort(); string authListenUri = "http://localhost:" + listenPort + "/auth_response/"; httpListener = new HttpListener(); httpListener.Prefixes.Add(authListenUri); httpListener.Start(); // send authorization request: open in default browser string authRequestUri = RequestAccessApi + "?redirect_uri=" + Uri.EscapeDataString(authListenUri) + "&prompt=consent" + "&response_type=code" + "&client_id=" + clientIdentifier.GetID() + "&scope=" + Uri.EscapeDataString(AccessScopeAppSettings) + "&access_type=offline"; Process.Start(authRequestUri); // wait for reponse string authorizationCode = null; { HttpListenerContext listenContext = null; try { listenContext = await Task.Factory.FromAsync(httpListener.BeginGetContext(null, null), httpListener.EndGetContext); } catch (Exception) { listenContext = null; } if (listenContext != null) { Uri requestUrl = listenContext.Request.Url; ILookup <string, string> queryLookup = requestUrl.Query.TrimStart('?') .Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries) .Select(k => k.Split('=')) .Where(k => k.Length == 2) .ToLookup(a => a[0], a => Uri.UnescapeDataString(a[1]), StringComparer.OrdinalIgnoreCase); authorizationCode = queryLookup["code"].FirstOrDefault(); string responseString = "<html><title>Google account verification</title><body>Received verification code. You may now close this window.</body></html>"; byte[] buffer = Encoding.UTF8.GetBytes(responseString); HttpListenerResponse listenResponse = listenContext.Response; listenResponse.ContentLength64 = buffer.Length; listenResponse.OutputStream.Write(buffer, 0, buffer.Length); listenResponse.OutputStream.Close(); } } // send token grant request: no user ui needed Token resultToken = null; if (!string.IsNullOrEmpty(authorizationCode)) { HttpContent tokenGrantContent = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("code", authorizationCode), new KeyValuePair <string, string>("redirect_uri", authListenUri), new KeyValuePair <string, string>("client_id", clientIdentifier.GetID()), new KeyValuePair <string, string>("client_secret", clientIdentifier.GetSecret()), new KeyValuePair <string, string>("scope", AccessScopeAppSettings), new KeyValuePair <string, string>("grant_type", "authorization_code"), }); tokenGrantContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); try { HttpClient client = new HttpClient(); HttpResponseMessage tokenGrantResponse = await client.PostAsync(TokenApi, tokenGrantContent); if (tokenGrantResponse.IsSuccessStatusCode) { string replyJson = await tokenGrantResponse.Content.ReadAsStringAsync(); resultToken = CreateToken(replyJson); } } catch (Exception) { } } if (httpListener != null && httpListener.IsListening) { httpListener.Close(); httpListener = null; } return(resultToken); }
public static void Main(string[] args) { int parentProcessID; string basePath = ""; // For testing purposes... if (args.Length == 0) { Console.WriteLine("No commandline arguments, harcoded debug mode..."); parentProcessID = 0; } else { basePath = args[0]; } if (args.Length >= 2) { parentProcessID = int.Parse(args[1]); } else { parentProcessID = 0; } // Automatically quit bundle server when Unity exits if (parentProcessID != 0) { Thread thread = new Thread(WatchDog); thread.Start(parentProcessID); } bool detailedLogging = false; int port = 7888; Console.WriteLine("Starting up asset bundle server.", port); Console.WriteLine("Port: {0}", port); Console.WriteLine("Directory: {0}", basePath); HttpListener listener = new HttpListener(); /* * IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName ()); * foreach (IPAddress ip in host.AddressList) * { * //if (ip.AddressFamily.ToString() == "InterNetwork") * { * Console.WriteLine(ip.AddressFamily.ToString() + " - " + ip.ToString()); * } * } */ listener.Prefixes.Add(string.Format("http://*:{0}/", port)); listener.Start(); while (true) { Console.WriteLine("Waiting for request..."); HttpListenerContext context = listener.GetContext(); WriteFile(context, basePath, detailedLogging); } }
public Task Start() { return(Task.Run(() => { _listener = new HttpListener(); _listener.Prefixes.Add($"http://*****:*****@"^\/(\d+)?$")) { var pageID = context.Request.RawUrl == "/" ? 0 : int.Parse(context.Request.RawUrl.Substring(1)); var page = context.Request.HttpMethod == "GET" ? _db.GetCollection($"$dump({pageID})").Query().FirstOrDefault() : GetPost(context.Request.InputStream); if (page == null) { body = $"Page {pageID} not found in database"; } else { var dump = new HtmlPageDump(page); body = dump.Render(); } } else if (Regex.IsMatch(context.Request.RawUrl, @"^\/list/(\d+)$")) { var pageID = int.Parse(context.Request.RawUrl.Substring(6)); var exp = new HtmlPageList(_db.GetCollection($"$page_list({pageID})").Query().Limit(1000).ToEnumerable()); body = exp.Render(); } else { body = "Url not found"; status = 404; } var message = Encoding.UTF8.GetBytes(body); context.Response.StatusCode = status; context.Response.ContentType = "text/html"; context.Response.ContentLength64 = message.Length; context.Response.OutputStream.Write(message, 0, message.Length); }); } catch (Exception) { } } })); }
public void Start() { server.Start(); server.BeginGetContext(serverCallback, server); isRunning = true; }
/// <summary> /// 启动Http服务器 /// </summary> public void Start() { httpListener.Start(); httpListener.BeginGetContext(new AsyncCallback(GetContext), httpListener); }
static void Main(string[] args) { var portAddr = int.Parse(args.Length >= 1? args[0]: "3010"); var folder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (args.Length >= 2) { folder = args[1]; } #if TRACE var progFolder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); var traceFullName = Path.Combine(progFolder, "SimpleServer", DateTime.Now.ToString("s").Replace(":", "-") + ".txt"); var traceFolderInfo = new DirectoryInfo(Path.GetDirectoryName(traceFullName)); traceFolderInfo.Create(); var traceFile = File.Create(traceFullName); var listener = new TextWriterTraceListener(traceFile); Trace.Listeners.Add(listener); Trace.AutoFlush = true; #endif var server = new HttpListener(); var success = false; var adder = 0; for (var n = 0; !success; n++) { adder = Fib(n); server.Prefixes.Add($"http://127.0.0.1:{portAddr + adder}/"); server.Prefixes.Add($"http://*****:*****@"^[-/.a-z0-9A-Z]+$"); Trace.WriteLine($"Listening to {portAddr}"); while (true) { var context = server.GetContext(); var response = context.Response; string page = context.Request.Url.LocalPath; if (string.IsNullOrEmpty(page) || page == "/") { page = "/index.html"; } Trace.WriteLine($"Recieved request {context.Request.HttpMethod} {page}"); if (!charTest.Match(page).Success || page.StartsWith(".") || page.Contains("/.")) { context.Response.StatusCode = 400; } // GetMeta puts a wave file and expects a response so don't add context.Request.HttpMethod.ToLower() == "get" && else if (File.Exists(folder + page)) { page = folder + page; Trace.WriteLine($"File found {page}"); var st = response.OutputStream; try { if (Path.DirectorySeparatorChar != '/') { page = page.Replace("/", Path.DirectorySeparatorChar.ToString()); } Trace.WriteLine($"Opening {page}"); using (var reader = new FileStream(page, FileMode.Open, FileAccess.Read)) { Trace.WriteLine($"File open for reading"); response.ContentLength64 = reader.Length; Trace.WriteLine($"Length = {reader.Length}"); const int blockSize = 10024; var buffer = new byte[blockSize]; for (var c = reader.Length; c > 0;) { var bytesRead = reader.Read(buffer, 0, blockSize); Trace.WriteLine($"Bytes read {bytesRead}"); st.Write(buffer, 0, bytesRead); c -= bytesRead; } reader.Close(); } } catch (Exception e) { Trace.WriteLine(e); throw; } } context.Response.Close(); Trace.WriteLine($"Response sent"); } }
public void run() { if (!DataBase.connect()) { Console.WriteLine("Error, database not connected!"); return; } listener.Start(); Console.WriteLine("Listening for connections on {0}", url); Thread minuteTasksThread = new Thread(delegate() { while (true) { if (!DataBase.getEndedSaleNotifications()) { Console.WriteLine("Couldn't generate sale end notifications!"); } Thread.Sleep(60000); } }); //so it exits when app exits minuteTasksThread.IsBackground = true; minuteTasksThread.Start(); while (true) { /*if(Console.In.Peek() != -1) * { * string command = Console.ReadLine(); * if (command == "stop") * { * break; * } * else * { * Console.WriteLine("unrecognized command: '" + command + "'"); * } * }*/ HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; Console.WriteLine("[" + DateTime.Now.ToLongTimeString() + "] " + request.Url.ToString()); byte[] data; try { switch (request.HttpMethod) { case "GET": data = handleGET(request); break; case "POST": data = handlePOST(request); break; default: data = null; break; } if (data == null) { data = Encoding.UTF8.GetBytes("{}"); response.StatusCode = 400; } }catch (Exception e) { data = Encoding.UTF8.GetBytes("{}"); response.StatusCode = 500; Console.WriteLine(e); } response.ContentType = "application/json"; response.ContentEncoding = Encoding.UTF8; response.ContentLength64 = data.LongLength; response.OutputStream.Write(data, 0, data.Length); response.Close(); } listener.Close(); }
private void button1_Click(object sender, EventArgs e) { if (!GlobalData.LoggedIn) { if (!memloging) { try { HttpListener l = new HttpListener(); l.Prefixes.Add("http://*****:*****@"\5Daddy Landing Monitor.exe.config"); if (Regex.IsMatch(filecont, "<!--" + memloginName + "|" + memloginToken + "-->")) { string newrplc = Regex.Replace(filecont, "<!--" + memloginName + "|" + memloginToken + "-->", string.Empty); File.WriteAllText(Environment.CurrentDirectory + @"\5Daddy Landing Monitor.exe.config", newrplc); button1.Text = "Login with Discord"; } } } GlobalData.Username = ""; GlobalData.LoggedIn = false; memloginToken = ""; memloginName = ""; memloging = false; timer1.Enabled = false; label4.Text = "Not logged in.."; label4.ForeColor = Color.Red; } }
/// <summary> /// Start listening on the specified interface /// </summary> public void BeginListening() { if (!listening && (listenThread == null || listenThread.ThreadState != ThreadState.Running)) { // 0 means disable the web server if (MasterServer.Settings.WebServerListenPort == 0) { MasterServer.Log("[WEB] Web server is disabled."); return; } // Get all loaded request handler modules requestHandlers = ModuleManager.GetModules <IRequestHandler>(); // Sort the request handlers into priority order, highest first requestHandlers.Sort(); // Flag to indicate the server is active listening = true; listener = new HttpListener(); log = ModuleManager.GetModule <IWebLogWriter>(); try { WebServer.ListenPorts = MasterServer.Settings.WebServerListenPort.ToString(); // Attempt to bind specified addresses and prefixes foreach (string listenAddress in MasterServer.Settings.WebServerListenAddresses) { listener.Prefixes.Add(String.Format("http://{0}:{1}/", listenAddress, MasterServer.Settings.WebServerListenPort)); } MasterServer.Log("[WEB] Starting web server on port {0}", MasterServer.Settings.WebServerListenPort); listener.Start(); MasterServer.Log("[WEB] Web server started ok."); // Start the listen thread listenThread = new Thread(new ThreadStart(ListenerThread)); listenThread.Start(); } catch (HttpListenerException ex) { WebServer.ListenPorts = "-"; if (ex.ErrorCode == 32) { MasterServer.Log("[WEB] Error, port already in use!"); } else { MasterServer.Log("[WEB] Error binding listen port: {0}", ex.Message); } listening = false; listener = null; // Release request handler modules ModuleManager.ReleaseModules <IRequestHandler>(); ModuleManager.ReleaseModule <IWebLogWriter>(); } catch (Exception ex) { WebServer.ListenPorts = "-"; MasterServer.Log("[WEB] Error binding listen port: {0}", ex.Message); listening = false; listener = null; // Release request handler modules ModuleManager.ReleaseModules <IRequestHandler>(); ModuleManager.ReleaseModule <IWebLogWriter>(); } } else { MasterServer.Log("[WEB] Error starting web server. Web server already running"); //throw new InvalidOperationException("Web server is already listening"); } }
public MonitorListener(int port) { listener = new HttpListener(); listener.Prefixes.Add($"http://*:{port}/Status/"); listener.Start(); }
public async Task MultipleRequestsToSameEndpointWithNtlmShouldNotFail() { var uri = new Uri("http://localhost:52179/platibus/"); var clientPool = new HttpClientPool(); var testCompletionSource = new TaskCompletionSource <int>(); var testComplete = testCompletionSource.Task; var httpListener = new HttpListener { AuthenticationSchemes = AuthenticationSchemes.Ntlm, Prefixes = { uri.ToString() } }; Task httpListenerLoop = null; try { httpListener.Start(); httpListenerLoop = Task.Run(async() => { while (httpListener.IsListening) { var contextReceipt = httpListener.GetContextAsync(); if (await Task.WhenAny(testComplete, contextReceipt) == testComplete) { break; } var context = await contextReceipt; await context.Request.InputStream.CopyToAsync(context.Response.OutputStream); context.Response.StatusCode = 200; context.Response.Close(); } }); var clientTasks = Enumerable.Range(1, 10) .Select(i => Task.Run(async() => { // ReSharper disable once AccessToDisposedClosure using (var client = await clientPool.GetClient(uri, new DefaultCredentials())) { var content = "test" + (i + 1); var response = await client.PostAsync("test", new StringContent(content)); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(content, await response.Content.ReadAsStringAsync()); return(response); } })); var responses = await Task.WhenAll(clientTasks); Assert.Equal(10, responses.Length); } finally { if (httpListenerLoop != null) { testCompletionSource.TrySetResult(0); httpListenerLoop.Wait(TimeSpan.FromSeconds(5)); } if (httpListener.IsListening) { httpListener.Stop(); } httpListener.Close(); clientPool.Dispose(); } }
public void Start() { try { IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName()); // IPAddress ipAddr = ipHost.AddressList[3]; //string ip = ""; //for (int i = 1; i < ipHost.AddressList.Length; i++) //{ // ip = ipHost.AddressList[i].ToString(); server.Prefixes.Add("http://" + "101.99.28.148" + ":1111/"); //} // server.Start(); try { server.Start(); //Throws Exception } catch (HttpListenerException ex) { if (ex.Message.Contains("Access is denied")) { return; } else { throw; } } Console.WriteLine("Listening..."); while (true) { HttpListenerContext context = server.GetContext(); HttpListenerResponse response = context.Response; string page = context.Request.Url.ToString(); //page = context.Request.Url.LocalPath; ; // if (page == string.Empty) if (page.Contains("dhcprestart.html")) { string msg = ""; // tao file conf #region Tao file config try { Class.NW_Dhcp_Customer cls = new Class.NW_Dhcp_Customer(); DataTable dt = cls.NW_Dhcp_Customer_Getlist(); if (dt.Rows.Count > 0) { if (System.IO.File.Exists(@"dhcpd.conf.temp")) { string txt = System.IO.File.ReadAllText(@"dhcpd.conf.temp"); string CPEDynamic = ""; string CPEStatic = ""; string PoolModem = ""; Class.NW_Dhcp_Ip clsIP = new Class.NW_Dhcp_Ip(); Class.NW_Dhcp_Customer clsModem = new Class.NW_Dhcp_Customer(); DataTable dtCPEDynamic = clsIP.NW_Dhcp_Ip_GetbyCPEDynamic(); DataTable dtCPEStatic = clsIP.NW_Dhcp_Ip_GetbyCPEStatic(); DataTable dtPoolModem = clsIP.NW_Dhcp_Ip_GetbyPoolModem(); #region CPEDynamic for (int i = 0; i < dtCPEDynamic.Rows.Count; i++) { CPEDynamic += "\tsubnet " + dtCPEDynamic.Rows[i]["PoolIp"].ToString() + " netmask " + dtCPEDynamic.Rows[i]["SubnetMask"].ToString() + " {\n" + "\t\tauthoritative;\n" + "\t\toption subnet-mask " + dtCPEDynamic.Rows[i]["SubnetMask"].ToString() + ";\n" + "\t\toption domain-name-servers " + dtCPEDynamic.Rows[i]["Dns"].ToString() + ";\n" + "\t\toption routers " + dtCPEDynamic.Rows[i]["Router"].ToString() + ";\n" + "\t\toption broadcast-address " + dtCPEDynamic.Rows[i]["Broadcast"].ToString() + ";\n" + "\t\tpool {\n" + "\t\trange " + dtCPEDynamic.Rows[i]["Range"].ToString() + ";\n" + "\t\t}\n" + "\t}\n" + "\tgroup {\n" + "\t\tuse-host-decl-names on;\n" + "\t}\n"; } #endregion #region CPEStatic for (int i = 0; i < dtCPEStatic.Rows.Count; i++) { clsModem.PoolIp = dtCPEStatic.Rows[i]["PoolIp"].ToString(); DataTable dtmodem = clsModem.NW_Dhcp_Customer_GetbyPoolPublic(); string txtmodem = ""; for (int j = 0; j < dtmodem.Rows.Count; j++) { string ipcpe = dtmodem.Rows[j]["IpPublic"].ToString(); ipcpe = ipcpe.Replace(":", "-"); string reIPcpe = dtmodem.Rows[j]["MacPc"].ToString().Replace(":", ""); txtmodem += "\t\t# PC an Modem " + dtmodem.Rows[j]["IpAddress"].ToString() + " " + dtmodem.Rows[j]["Note"].ToString() + " Kunde " + dtmodem.Rows[j]["CustomerCode"].ToString() + " " + dtmodem.Rows[j]["CustomerName"].ToString() + "\n" + "\t\thost " + ipcpe + " {\n" + "\t\t\thardware ethernet " + dtmodem.Rows[j]["MacPc"].ToString() + " ;\n" + "\t\t\tfixed-address " + dtmodem.Rows[j]["IpPublic"].ToString() + ";\n" + "\t\t\toption host-name \"mt"+ reIPcpe + "\";\n" + "\t\t\tddns-hostname \"mt"+ reIPcpe + "\";\n" + "\t\t}\n"; } CPEStatic += "\tsubnet " + dtCPEStatic.Rows[i]["PoolIp"].ToString() + " netmask " + dtCPEStatic.Rows[i]["SubnetMask"].ToString() + " {\n" + "\t\tauthoritative;\n" + "\t\toption subnet-mask " + dtCPEStatic.Rows[i]["SubnetMask"].ToString() + ";\n" + "\t\toption domain-name-servers " + dtCPEStatic.Rows[i]["Dns"].ToString() + ";\n" + "\t\toption routers " + dtCPEStatic.Rows[i]["Router"].ToString() + ";\n" + "\t\toption broadcast-address " + dtCPEStatic.Rows[i]["Broadcast"].ToString() + ";\n" + "\t}\n" + "\tgroup {\n" + "\t\tuse-host-decl-names on;\n" + txtmodem + "\t}\n"; } #endregion #region CableMode for (int i = 0; i < dtPoolModem.Rows.Count; i++) { clsModem.PoolIp = dtPoolModem.Rows[i]["PoolIp"].ToString(); DataTable dtmodem = clsModem.NW_Dhcp_Customer_GetbyPool(); string listmodem = ""; for (int j = 0; j < dtmodem.Rows.Count; j++) { string cm = dtmodem.Rows[j]["MacAddress"].ToString(); cm = cm.Replace(":", ""); listmodem += "\t\t# " + dtmodem.Rows[j]["IpAddress"].ToString() + " Kunde " + dtmodem.Rows[j]["CustomerCode"].ToString() + " " + dtmodem.Rows[j]["CustomerName"].ToString() + "\n" + "\t\thost " + cm + " {\n" + "\t\t\thardware ethernet " + dtmodem.Rows[j]["MacAddress"].ToString() + " ; \n" + "\t\t\tfixed-address " + dtmodem.Rows[j]["IpAddress"].ToString() + ";\n" + "\t\t\toption host-name \"cm" + cm + "\";\n" + "\t\t\tddns-hostname \"cm" + cm + "\";\n" + "\t\t\toption bootfile-name \"" + dtmodem.Rows[j]["Bootfile"].ToString() + "\";\n" + "\t\t\tfilename \"" + dtmodem.Rows[j]["Bootfile"].ToString() + "\";\n" + "\t\t}\n"; } PoolModem += "\tsubnet " + dtPoolModem.Rows[i]["PoolIp"].ToString() + " netmask " + dtPoolModem.Rows[i]["SubnetMask"].ToString() + " {\n" + "\t\tauthoritative;\n" + "\t\toption subnet-mask " + dtPoolModem.Rows[i]["SubnetMask"].ToString() + ";\n" + "\t\toption routers " + dtPoolModem.Rows[i]["Router"].ToString() + ";\n" + "\t\toption broadcast-address " + dtPoolModem.Rows[i]["Broadcast"].ToString() + ";\n" + "\t}\n" + "\tgroup {\n" + "\t\tuse-host-decl-names on;\n" + listmodem + "\t}\n"; } #endregion txt = txt.Replace("<_CPEDynamic>", CPEDynamic); txt = txt.Replace("<_CPEStatic>", CPEStatic); txt = txt.Replace("<_modemip>", PoolModem); System.IO.File.WriteAllText(@"dhcpd.conf", txt); } else { msg = "file dhcpd.conf.temp not found!"; } } msg = "Create file success!"; } catch { msg = "Fail create to file.."; } #endregion #region UploadtoServer if (msg == "Create file success!") { msg += "\r\nTranfer file to SERVER "; Class.App.uploadFile("ftp://101.99.28.152/test/", Application.StartupPath + "/dhcpd.conf", "administrator", "831031"); try { msg += "Ok"; } catch { msg += "Fail"; } } #endregion //write respones byte[] buffer = Encoding.UTF8.GetBytes(msg); response.ContentLength64 = buffer.Length; Stream st = response.OutputStream; st.Write(buffer, 0, buffer.Length); st.Close(); } else { string msg = "Access Deny !"; byte[] buffer = Encoding.UTF8.GetBytes(msg); response.ContentLength64 = buffer.Length; Stream st = response.OutputStream; st.Write(buffer, 0, buffer.Length); st.Close(); } context.Response.Close(); } } catch { Stop(); Start(); } }
static void OldMain(string[] args) { Dictionary <string, BaseCDNModule> modules = new Dictionary <string, BaseCDNModule>(); modules.Add("dailymotion", new DailymotionModule("dailymotion")); modules.Add("youtube", new YoutubeModule("youtube")); if (Directory.Exists(".\\Modules\\")) { foreach (string file in Directory.GetFiles(".\\Modules\\")) { string name = Path.GetFileNameWithoutExtension(file); modules.Add(name, new ScriptedProvider(name, file)); Console.WriteLine("Loaded Module: " + name); } } client = new WebClient(); client.Encoding = Encoding.UTF8; HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://*:6672/"); listener.Start(); char[] pathSplit = { '/' }; while (listener.IsListening) { HttpListenerContext webContext = listener.GetContext(); webContext.Response.ContentEncoding = Encoding.UTF8; string[] pathing = webContext.Request.Url.LocalPath.Split(pathSplit, StringSplitOptions.RemoveEmptyEntries); //string requestType = string.Join("/", pathing, 1, pathing.Length - 1); string requestPath = string.Join("/", pathing); string moduleName = pathing[0]; Console.WriteLine("{0} - {1}: {2}", DateTime.Now, webContext.Request.RemoteEndPoint.Address, requestPath); bool sucess = false; if (modules.ContainsKey(moduleName)) { requestPath = string.Join("/", pathing, 1, pathing.Length - 1); BaseCDNModule module = modules[moduleName]; Console.WriteLine("-> Module " + moduleName); string result = null;// module.Request(requestPath, webContext.Request.QueryString); switch (requestPath) { case "browse": string query = webContext.Request.QueryString["query"]; int page = Convert.ToInt32(webContext.Request.QueryString["page"]); ContentSeriesInfo[] infos = module.Browse(query, page); result = string.Join("\n", (object[])infos); break; case "get_list": string listPath = webContext.Request.QueryString["path"]; ContentSeries series = module.GetContentList(listPath); result = series.Name + "\n" + string.Join("\n", (object[])series.Installments); break; case "get_link": string linkPath = webContext.Request.QueryString["path"]; result = string.Join("\n", (object[])module.GetContentLink(linkPath)); break; default: Console.WriteLine("-> Bad request: " + requestPath); break; } if (result != null) { byte[] data = Encoding.UTF8.GetBytes(result); sucess = WriteToOutputStream(data, webContext); } } webContext.Response.OutputStream.Close(); } }
private void ListenThread() { try { listener = new HttpListener(); foreach (string prefix in prefixes) { listener.Prefixes.Add(prefix); } listener.Start(); while (true) { HttpListenerContext context = listener.GetContext(); Debug.LogFormat("Recieved request from {0}.", context.Request.RemoteEndPoint.ToString()); context.Response.StatusCode = 200; lock (waitingContexts) { waitingContexts.AddLast(context); } } } catch(Exception e) { Debug.LogErrorFormat("Web server error at {0}.", e.Source); Debug.LogError(e.Message, this); } }
public void Start() { listener.Start(); StartListen(); }
public async Task <string> InitiateTokenRetrieval() { string state = RandomDataBase64Url(32); string redirectURI = ""; var http = new HttpListener(); foreach (var i in new int[] { 17236, 17284, 17287, 17291, 17296 }) { try { redirectURI = string.Format("http://{0}:{1}/", IPAddress.Loopback, i); http.Prefixes.Add(redirectURI); http.Start(); break; } catch (Exception e) { http = new HttpListener(); } } // Creates the OAuth 2.0 authorization request. string authorizationRequest = string.Format("{0}?response_type=code&scope=remote_control:all&client_id={1}&state={2}&redirect_uri={3}", _lIFXAuthorizationEndpoint, _options.LIFXClientId, state, HttpUtility.UrlEncode(redirectURI) ); Helpers.OpenBrowser(authorizationRequest); // Waits for the OAuth authorization response. var context = await http.GetContextAsync(); //Sends an HTTP response to the browser. var response = context.Response; string responseString = string.Format("<html><head><meta http-equiv='refresh' content='10;url=https://lifx.com'></head><body>Please return to the app.</body></html>"); var buffer = System.Text.Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; var responseOutput = response.OutputStream; Task responseTask = responseOutput.WriteAsync(buffer, 0, buffer.Length).ContinueWith((task) => { responseOutput.Close(); http.Stop(); Debug.WriteLine("HTTP server stopped."); }); // Checks for errors. if (context.Request.QueryString.Get("error") != null) { return(""); } if (context.Request.QueryString.Get("code") == null || context.Request.QueryString.Get("state") == null) { return(""); } // extracts the code var code = context.Request.QueryString.Get("code") ?? ""; var incoming_state = context.Request.QueryString.Get("state"); // Compares the receieved state to the expected value, to ensure that // this app made the request which resulted in authorization. if (incoming_state != state) { return(""); } // Starts the code exchange at the Token Endpoint. return(await PerformCodeExchange(code)); }
static void Main(string[] args) { StaticStore.ReadFromFile(); StaticStore.RebuildHashTables(); DynamicStore.ReadFromFile(); var srv = new HttpListener(); srv.Prefixes.Add("http://*:23455/"); srv.Start(); using (srv) { for (;;) { Handle(srv.GetContext()); } } }
private async void SignIn(IWindowService window) { // Generates state and Proof Key for Code Exchange values. var state = RandomDataBase64Url(32); var codeVerifier = RandomDataBase64Url(32); var codeChallenge = Base64UrlencodeNoPadding(Sha256(codeVerifier)); // Creates a redirect URI using an available port on the loopback address. var redirectUri = $@"http://{IPAddress.Loopback}:{GetRandomUnusedPort()}/"; // Creates an HttpListener to listen for requests on that redirect URI. var http = new HttpListener(); http.Prefixes.Add(redirectUri); http.Start(); // Creates the OAuth 2.0 authorization request. var authorizationRequest = string.Format(_authorizationRequest, _authorizationEndpoint, Uri.EscapeDataString(redirectUri), _clientID, state, codeChallenge, _codeChallengeMethod); // Opens request in the browser. System.Diagnostics.Process.Start(authorizationRequest); // Waits for the OAuth authorization response. var context = await http.GetContextAsync(); // Brings this app back to the foreground. window.Activate(); // Sends an HTTP response to the browser. var response = context.Response; var buffer = Encoding.UTF8.GetBytes(_responseString); response.ContentLength64 = buffer.Length; var responseOutput = response.OutputStream; var responseTask = responseOutput.WriteAsync(buffer, 0, buffer.Length).ContinueWith((task) => { responseOutput.Close(); http.Stop(); http.Close(); }); // Checks for errors. if (context.Request.QueryString.Get("error") != null) { throw new Exception(string.Format(ErrorMessages.OAuthAuthorizationError.GetDescription(), context.Request.QueryString.Get("error"))); } if (context.Request.QueryString.Get("code") == null || context.Request.QueryString.Get("state") == null) { throw new Exception(string.Format(ErrorMessages.InvalidAuthorizationResponse.GetDescription(), context.Request.QueryString)); } // extracts the code var code = context.Request.QueryString.Get("code"); var incomingState = context.Request.QueryString.Get("state"); // Compares the received state to the expected value, to ensure that // this app made the request which resulted in authorization. if (incomingState != state) { throw new Exception(string.Format(ErrorMessages.RequestInvalidState.GetDescription(), incomingState)); } // Starts the code exchange at the Token Endpoint. var accessToken = await PerformCodeExchange(code, codeVerifier, redirectUri); var userInfo = await GetUserInfo(accessToken); userInfo.Id = await SetUser(userInfo); window.ShowWindow(new Context(userInfo)); window.Close(); }
public void Run() { HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://localhost:8080/"); listener.Start(); // Wait for a request HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; // process the request string path = request.Url.AbsolutePath; string responseString; try { responseString = handler(context); } catch (Exception e) { responseString = e.ToString(); } // write the response HttpListenerResponse response = context.Response; System.IO.Stream output = response.OutputStream; if (!String.IsNullOrEmpty(responseString)) { byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; output.Write(buffer, 0, buffer.Length); } output.Close(); // shut down the listener listener.Stop(); }
public void Start() { Debug.WriteLine("{0} [FILE SERVER]: Started on {1}", DateTime.Now, _url); _listener.Start(); ServeFiles(); }
static void Main(string[] args) { db = new SQLiteConnection(ServerSettings.Default.ConnectionString); db.Open(); CreateTables(); bool running = true; Console.CancelKeyPress += (s, e) => { running = false; e.Cancel = true; }; Console.WriteLine("Press Ctrl+C to quit."); using (var http = new HttpListener()) { http.Prefixes.Add(ServerSettings.Default.Prefix); http.Start(); while (running) { HttpListenerContext context = null; try { var result = http.BeginGetContext(null, null); while (!result.IsCompleted) { if (running == false) goto quit; Thread.Sleep(0); } context = http.EndGetContext(result); switch (context.Request.HttpMethod) { case "POST": DispatchPost(context); break; default: DispatchGet(context); break; } } catch (Exception ex) { using (var sw = new StreamWriter(context.Response.OutputStream, Encoding.UTF8)) { sw.Write(ex.ToString()); } context.Response.StatusCode = 500; } finally { if (context != null) context.Response.Close(); } } quit: db.Close(); } }
private void AuthorizeSnip() { try { Process authorizationProcess = Process.Start( string.Format( CultureInfo.InvariantCulture, "{0}?client_id={1}&response_type={2}&redirect_uri={3}&scope={4}", this.authorizationAddress, ApplicationKeys.SpotifyClientId, this.responseType, this.callbackAddress, this.scopes )); HttpListener callbackListener = new HttpListener(); callbackListener.Prefixes.Add(this.callbackAddress); callbackListener.Start(); // block for now since authorization is absolutely required // eventually swap this to non-blocking (BeginGetContext) HttpListenerContext context = callbackListener.GetContext(); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; NameValueCollection nameValueCollection = request.QueryString; string callbackHtmlStart = "<!doctype html><html lang=en><head><meta charset=utf-8><style>html, body { height: 100%; margin: 0; padding: 0; } body { background-color: rgb(255, 255, 255); color: rgb(0, 0, 0); } div.wrapper { display: table; table-layout: fixed; width: 100%; height: 90%; } div.container { display: table-cell; vertical-align: middle; } div.centered { font-family: Arial, Helvetica, sans-serif; font-size: 1em; font-weight: normal; text-align: center; }</style><title>Snip</title></head><body><div class=wrapper><div class=container><div class=centered>"; string callbackHtmlEnd = "</div></div></div></body></html>"; string outputString = string.Empty; foreach (string keyValue in nameValueCollection.AllKeys) { switch (keyValue) { case "error": outputString = string.Format( CultureInfo.InvariantCulture, "{0}{1}{2}", callbackHtmlStart, "Well... you denied Snip access. That kind of defeats the purpose of Snip. You may close this window now, and Snip, you filthy swine.", callbackHtmlEnd); break; case "code": outputString = string.Format( CultureInfo.InvariantCulture, "{0}{1}{2}", callbackHtmlStart, "Thank you for authorizing Snip. You're the best! You may close this window now.", callbackHtmlEnd); this.authorizationCode = nameValueCollection[keyValue]; break; default: break; } } byte[] buffer = Encoding.UTF8.GetBytes(outputString); response.ContentLength64 = buffer.Length; Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); output.Close(); callbackListener.Stop(); } catch { // add error checking } }
private async Task <bool> CanConnectUsingOpenId(Connection connection) { try { using (var source = new CancellationTokenSource()) { var discoveryUrl = new Uri(new Uri(connection.Uri), "/" + OpenIdProviderMetadataNames.Discovery); var config = await OpenIdConnectConfigurationRetriever.GetAsync(discoveryUrl.ToString(), source.Token); var result = false; var closed = false; var authEndpoint = config.AuthorizationEndpoint + "?scope=email%20profile" + "&response_type=code" + "&redirect_uri=http://localhost:" + connection.RedirectPort + "&client_id=" + WebUtility.UrlEncode(connection.ClientId); await Runtime.InvokeAsync(() => { var window = new NavigationWindow() { WindowStartupLocation = WindowStartupLocation.CenterOwner, Owner = Application.Current?.MainWindow, Title = "Authenticate", ShowsNavigationUI = false, Source = new Uri(authEndpoint), Width = 500, Height = 400 }; var listener = new HttpListener(); listener.Prefixes.Add($"http://*:{ connection.RedirectPort }/"); listener.Start(); listener.BeginGetContext(x => { if (!listener.IsListening || closed) { return; } var context = listener.EndGetContext(x); var code = context.Request.QueryString["code"]; Runtime.Invoke(() => { result = !string.IsNullOrWhiteSpace(code); window.Close(); }); }, null); window.Closed += (s, e) => { closed = true; listener.Stop(); }; window.ShowDialog(); }); _log.DebugFormat("OpenID connection test {0}", result ? "passed" : "failed"); return(await Task.FromResult(result)); } } catch (Exception ex) { _log.Error("OpenID connection test failed", ex); return(await Task.FromResult(false)); } }
protected override void DoStart() { if (m_Prefixes.Count == 0) { throw new WaveException(StringConsts.SERVER_NO_PREFIXES_ERROR.Args(Name)); } if (!s_Servers.Register(this)) { throw new WaveException(StringConsts.SERVER_COULD_NOT_GET_REGISTERED_ERROR.Args(Name)); } try { if (m_Gate != null) { if (m_Gate is Service) { ((Service)m_Gate).Start(); } } if (m_Dispatcher == null) { m_Dispatcher = new WorkDispatcher(this); } m_Dispatcher.Start(); m_AcceptSemaphore = new Semaphore(m_ParallelAccepts, m_ParallelAccepts); m_WorkSemaphore = new Semaphore(m_ParallelWorks, m_ParallelWorks); m_AcceptThread = new Thread(acceptThreadSpin); m_AcceptThread.Name = "{0}-AcceptThread".Args(Name); m_InstrumentationThread = new Thread(instrumentationThreadSpin); m_InstrumentationThread.Name = "{0}-InstrumentationThread".Args(Name); m_InstrumentationThreadWaiter = new AutoResetEvent(false); m_Listener = new HttpListener(); foreach (var prefix in m_Prefixes) { m_Listener.Prefixes.Add(prefix); } BeforeListenerStart(m_Listener); m_Listener.Start(); AfterListenerStart(m_Listener); m_Listener.IgnoreWriteExceptions = m_IgnoreClientWriteErrors; if (m_KernelHttpQueueLimit != DEFAULT_KERNEL_HTTP_QUEUE_LIMIT) { PlatformUtils.SetRequestQueueLimit(m_Listener, m_KernelHttpQueueLimit); } } catch { closeListener(); if (m_AcceptSemaphore != null) { m_AcceptSemaphore.Dispose(); m_AcceptSemaphore = null; } if (m_WorkSemaphore != null) { m_WorkSemaphore.Dispose(); m_WorkSemaphore = null; } if (m_AcceptThread != null) { m_AcceptThread = null; } if (m_Dispatcher != null) { m_Dispatcher.WaitForCompleteStop(); } if (m_Gate != null && m_Gate is Service) { ((Service)m_Gate).WaitForCompleteStop(); } s_Servers.Unregister(this); throw; } m_InstrumentationThread.Start(); m_AcceptThread.Start(); }
public static void Start() { Listener.Start(); Listener.BeginGetContext(new AsyncCallback(HandleHttpRequest), Listener); }
public static void RunHttpServer() { var listener = new HttpListener(); String host = "http://localhost:8082/"; listener.Prefixes.Add(host); Console.WriteLine("Listening.."); listener.Start(); while (true) { try { var context = listener.GetContext(); var response = context.Response; var request = context.Request; response.StatusCode = 200; response.SendChunked = true; Stream body = request.InputStream; if (body == null) { return; } else { List<Message> messages = service.ParseReceivedMessages(body); foreach (Message message in messages) { String chat = message.GetChatId(); String messageText = message.GetMessageText().ToLower(); if (message.GetAttachments().Count > 0) { service.SendMessage(chat, "You send a media message / an attachment"); } else if (messageText.Equals("send a photo")) { service.SendImage(chat, "here's an image", "https://raw.githubusercontent.com/mediaelement/mediaelement-files/master/big_buck_bunny.jpg", null, null, null); } else if (messageText.Equals("send a video")) { service.SendVideo(chat, "here's a video", "https://raw.githubusercontent.com/mediaelement/mediaelement-files/master/big_buck_bunny.mp4", null, null, 1055736); } else if (messageText.Equals("send a file")) { service.SendFile(chat, "here's a general file", "http://unec.edu.az/application/uploads/2014/12/pdf-sample.pdf", null, null, "cloudrailFile.pdf", 7945); } else if (messageText.Equals("give me a choice")) { List<MessageButton> buttons1 = new List<MessageButton> { new MessageButton("Yay!", "postback", "https://raw.githubusercontent.com/mediaelement/mediaelement-files/master/big_buck_bunny.jpg", "Yay!"), new MessageButton("That's cool!", "postback", "https://raw.githubusercontent.com/mediaelement/mediaelement-files/master/big_buck_bunny.jpg", "That's cool!") }; List<MessageButton> buttons2 = new List<MessageButton> { new MessageButton("Nay!", "postback", "https://raw.githubusercontent.com/mediaelement/mediaelement-files/master/big_buck_bunny.jpg", "Nay!"), new MessageButton("Why would I do that?", "postback", "https://raw.githubusercontent.com/mediaelement/mediaelement-files/master/big_buck_bunny.jpg", "Why would I do that?") }; List<MessageItem> mItems = new List<MessageItem> { new MessageItem("CloudRail", "Implement all services with one common code", "https://raw.githubusercontent.com/mediaelement/mediaelement-files/master/big_buck_bunny.jpg", buttons1), new MessageItem("REST APIs", "Bother with a different API for every service", "https://raw.githubusercontent.com/mediaelement/mediaelement-files/master/big_buck_bunny.jpg", buttons2) }; service.SendCarousel(chat, mItems); } else if (messageText != null) { service.SendMessage(chat, "You send a new message at time " + message.GetSendAt() + " with ID " + message.GetMessageId() + " and content \"" + messageText + "\""); } } } } catch(Exception e) { Console.WriteLine(e); } } }
public async Task Start() { _listener.Start(); await ListenPort(); }
public ReplayServer(string gameId, string region) { string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (directoryName != null) { string dir = directoryName.Replace("file:\\", ""); if (!Directory.Exists(Path.Combine(dir, "cabinet", gameId + "-" + region))) { Console.WriteLine("Cannot find replay in: " + dir + " " + gameId + " " + region); Console.ReadLine(); return; } latestChunk = 1; nextChunk = 2; latestKeyframe = 1; gameFolder = Path.Combine(dir, "cabinet", gameId + "-" + region); } var di = new DirectoryInfo(gameFolder); FileInfo[] files = di.GetFiles("chunk-*"); foreach ( int chunkId in files.Select(f => Convert.ToInt32(f.Name.Replace("chunk-", ""))) .Where(chunkId => chunkId > lastChunk)) { lastChunk = chunkId; } files = di.GetFiles("key-*"); foreach ( int keyId in files.Select(f => Convert.ToInt32(f.Name.Replace("key-", ""))) .Where(keyId => keyId < latestKeyframe)) { latestKeyframe = keyId; } String token = File.ReadAllText(Path.Combine(gameFolder, "token")); var serializer = new JavaScriptSerializer(); var deserializedJson = serializer.Deserialize <Dictionary <string, object> >(token); endStartupChunkId = Convert.ToInt32(deserializedJson["endStartupChunkId"]); startGameChunkId = Convert.ToInt32(deserializedJson["startGameChunkId"]); Console.WriteLine("Starting replay server... Close this window after your replay has finished"); listener = new HttpListener(); listener.Prefixes.Add("http://127.0.0.1:5651/observer-mode/rest/consumer/"); listener.Start(); Console.WriteLine("Listening..."); timeLastChunkServed = DateTime.Now; while (true) { HandleQuery(); } }
/// <summary> /// Accept secure connections. /// </summary> /// <param name="address">IP Address to listen on, use <see cref="IPAddress.Any"/> to accept connections on all IP Addresses / network cards.</param> /// <param name="port">Port to listen on. 80 can be a good idea =)</param> /// <param name="certificate">Certificate to use</param> /// <exception cref="ArgumentNullException"><c>address</c> is null.</exception> /// <exception cref="ArgumentException">Port must be a positive number.</exception> public void Start(IPAddress address, int port, X509Certificate certificate) { if (address == null) throw new ArgumentNullException("address"); if (port <= 0) throw new ArgumentException("Port must be a positive number."); if (_httpsListener != null) return; Init(); _httpsListener = new HttpListener(address, port, _components.Get<IHttpContextFactory>(), certificate); _httpsListener.LogWriter = LogWriter; _httpsListener.RequestReceived += OnRequest; _httpsListener.Start(5); _httpsListener.ExceptionThrown += _exceptionHandler; }
public void Start1() { HttpListener listener = new HttpListener(); listener.Start(); }
static void Main(string []args) { if(args.Length != 2) { Console.WriteLine("Error: please specify URI to listen on and Authentication type to use:\nAuthListener.exe ServerURI AuthenticationScheme"); return; } string serverUri = args[0]; AuthenticationSchemes authScheme; switch(args[1].ToLower()) { case "none": authScheme = AuthenticationSchemes.None; break; case "anonymous": authScheme = AuthenticationSchemes.Anonymous; break; case "basic": authScheme = AuthenticationSchemes.Basic; break; case "digest": authScheme = AuthenticationSchemes.Digest; break; case "ntlm": authScheme = AuthenticationSchemes.Ntlm; break; case "negotiate": authScheme = AuthenticationSchemes.Negotiate; break; case "integrated": authScheme = AuthenticationSchemes.IntegratedWindowsAuthentication; break; default: Console.WriteLine("Error: unrecognized AuthenticationScheme:{0}", args[1]); return; } HttpListener listener = new HttpListener(); listener.Prefixes.Add(serverUri); listener.AuthenticationSchemes = authScheme; listener.Start(); Console.WriteLine("Listening..."); HttpListenerContext context = listener.GetContext(); Console.WriteLine("Received request..."); StreamWriter writer = new StreamWriter(context.Response.OutputStream); // Verify correct authentication scheme was used. if (!VerifyAuthenticationScheme(listener.AuthenticationSchemes, context)) { context.Response.StatusCode = (int)HttpStatusCode.ExpectationFailed; writer.Write("Error authentication validation failed"); } context.Response.Close(); }
/// <summary> /// Start the ASP listener, and Connects to the stats database /// </summary> public static void Start() { // Can't start if we are already running! if (IsRunning) { return; } // === Try to connect to the database using (StatsDatabase Database = new StatsDatabase()) { if (!Database.TablesExist) { string message = "In order to use the Private Stats feature of this program, we need to setup a database. " + "You may choose to do this later by clicking \"Cancel\". Would you like to setup the database now?"; DialogResult R = MessageBox.Show(message, "Stats Database Setup", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (R == DialogResult.Yes) { SetupManager.ShowDatabaseSetupForm(DatabaseMode.Stats, MainForm.Instance); } // Call the stopped event to Re-enable the main form's buttons Stopped(null, EventArgs.Empty); return; } // Initialize the stats manager StatsManager.Load(Database); // Drop the SQLite ip2nation country tables (old table versions) if (Database.DatabaseEngine == DatabaseEngine.Sqlite) { string query = "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='ip2nation'"; if (Database.ExecuteScalar <bool>(query)) // 0 count converts to false { Database.Execute("DROP TABLE IF EXISTS 'ip2nation';"); Database.Execute("DROP TABLE IF EXISTS 'ip2nationcountries';"); Database.Execute("VACUUM;"); } } } // === Compile our templates string path = Path.Combine(Program.RootPath, "Web", "Bf2Stats", "Views"); foreach (string file in Directory.EnumerateFiles(path, "*.cshtml")) { // If this template file is loaded already, then skip string fileName = Path.GetFileName(file); if (Engine.Razor.IsTemplateCached(fileName, ModelType)) { continue; } // Open the file, and compile it try { using (FileStream stream = File.OpenRead(file)) using (StreamReader reader = new StreamReader(stream)) Engine.Razor.Compile(reader.ReadToEnd(), fileName, ModelType); } catch (TemplateCompilationException e) { // Show the Exception form so the user can view DialogResult Res = ExceptionForm.ShowTemplateError(e, file); // If the user clicked "Quit", we stop if (Res == DialogResult.Abort) { return; } } } // === Load XML stats and awards files Bf2StatsData.Load(); BackendAwardData.BuildAwardData(); // Start the Listener and accept new connections try { Listener.Start(); Listener.BeginGetContext(HandleRequest, Listener); } catch (ObjectDisposedException) { // If we are disposed (happens when port 80 was in use already before, and we tried to start) // Then we need to start over with a new Listener CreateHttpListener(); Listener.Start(); Listener.BeginGetContext(HandleRequest, Listener); } // Fire Startup Event Started(null, EventArgs.Empty); }