internal HttpListenerContext (HttpConnection cnc) { this.cnc = cnc; err_status = 400; request = new HttpListenerRequest (this); response = new HttpListenerResponse (this); }
internal HttpListenerContext(HttpConnection cnc, ILogger logger) { this.cnc = cnc; _logger = logger; request = new HttpListenerRequest(this); response = new HttpListenerResponse(this, _logger); }
public HttpListenerCommunicationContext(IHost host, HttpListenerContext nativeContext) { ServerErrors = new List<Error>(); PipelineData = new PipelineData(); _host = host; User = nativeContext.User; Request = new HttpListenerRequest(this, nativeContext.Request); Response = new HttpListenerResponse(this, nativeContext.Response); }
static void ApiResponse(HttpListenerResponse response, HttpListenerRequest request) { response.StatusCode = 200; response.ContentType = "application/json"; ApiData r = new ApiData(); r.Status = 200; r.Value = "foo"; var serializer = new DataContractJsonSerializer(typeof(ApiData)); serializer.WriteObject(response.OutputStream, r); }
public static string SendInfo(HttpListenerRequest request) { string context = ""; Boolean succeeded = false; int count = 0; SerialPort serialPort = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One); while (!succeeded) { try { serialPort.Open(); int cm1 = Convert.ToInt32(serialPort.ReadLine()); int cm2 = Convert.ToInt32(serialPort.ReadLine()); if (cm1 >= 30) { context = "false:" + cm1.ToString(); Console.WriteLine(context); } else { context = "true:" + cm1.ToString(); Console.WriteLine(context); } succeeded = true; if (cm1 != cm2) { succeeded = false; count++; } if (count>=9){ context = "false:outOfRange"; Console.WriteLine(context); succeeded = true; } } catch (Exception ex) { context = "open error " + ex.Message; } finally { serialPort.Close(); } } return string.Format(context); }
private static string ShutdownServer(HttpListenerRequest request) { manualResetEvent.Set(); return("Server Terminated"); }
private static string IsTokenSet(HttpListenerRequest arg) { return(TokenService.IsTokenSet().ToString()); }
public void HandleGet(HttpListenerRequest request, HttpListenerResponse response) { response.StatusCode = 404; response.WriteResponse("404 Page Not Found"); }
private static string GetApi(KptRepository db, HttpListenerRequest req, Command cmd) { string responseString; if (cmd.IsUsers && cmd.UserId == 0 && !cmd.IsKptBoards) { // GET /v1/users/ Console.WriteLine("人の一覧"); var sb = new StringBuilder("["); var users = db.GetUsers(); foreach (var user in users) { sb.Append("{"); sb.Append(string.Format($@"""userId"":{user.UserId},")); sb.Append(string.Format($@"""name"":""{user.Name}""")); sb.Append("},"); } if (sb.Length > 0) { sb.Remove(sb.Length - 1, 1); } sb.Append("]"); return(sb.ToString()); } if (cmd.IsUsers && cmd.UserId != 0 && !cmd.IsKptBoards) { // GET /v1/users/n Console.WriteLine("特定の人の詳細"); var user = db.UserFindById(cmd.UserId); var sb = new StringBuilder("{"); sb.Append(string.Format($@"""userId"":{user.UserId},")); sb.Append(string.Format($@"""name"":""{user.Name}"",")); if (user.Age == null) { sb.Append(string.Format($@"""age"":null")); } else { sb.Append(string.Format($@"""age"":{user.Age}")); } sb.Append("}"); return(sb.ToString()); } if (cmd.IsUsers && cmd.UserId != 0 && cmd.IsKptBoards && cmd.KptBoardId == 0) { // GET /v1/users/n/kptboards Console.WriteLine("特定の人のボードの一覧"); // User user = db.UserFindById(cmd.userId); var kptBoards = db.GetKptBoardsByUserId(cmd.UserId); var sb = new StringBuilder("["); foreach (var kptBoard in kptBoards) { sb.Append("{"); sb.Append(string.Format($@"""boardId"":{kptBoard.KptBoardId},")); sb.Append(string.Format($@"""time"":""{kptBoard.Time}"",")); sb.Append(string.Format($@"""keep"":""{kptBoard.Keep}"",")); sb.Append(string.Format($@"""problem"":""{kptBoard.Problem}"",")); sb.Append(string.Format($@"""try"":""{kptBoard.Try}""")); sb.Append("},"); } if (sb.Length > 0) { sb.Remove(sb.Length - 1, 1); } sb.Append("]"); return(sb.ToString()); } if (cmd.IsUsers && cmd.UserId != 0 && cmd.IsKptBoards && cmd.KptBoardId != 0) { // GET /v1/users/n/kptboards/n Console.WriteLine("特定の人の特定のボードの詳細"); var kptBoard = db.GetKptBoardsById(cmd.UserId, cmd.KptBoardId); return(responseString = string.Format(@"{{""boardId"":{0},""date"":""{1}"",""keep"":""{2}"",""problem"":""{3}"",""try"":""{4}""}}", kptBoard.KptBoardId, kptBoard.Time, kptBoard.Keep, kptBoard.Problem, kptBoard.Try)); } throw new ArgumentException("指定したAPIがありません。GET " + cmd.ToString()); }
public HttpListenerRequestWrapper(HttpListenerRequest request) : this(null, request) { }
private AuthenticationSchemes SelectAnonymousAndBasicSchemes(HttpListenerRequest request) { return(AuthenticationSchemes.Anonymous | AuthenticationSchemes.Basic); }
/// <summary> /// This methods is the start of incoming HTTP request handling. /// </summary> /// <param name="context"></param> public virtual void HandleRequest(HttpListenerContext context) { HttpListenerRequest request = context.Request; using (HttpListenerResponse response = context.Response) { OSHttpRequest req = new OSHttpRequest(context); OSHttpResponse resp = new OSHttpResponse(context); if (request.HttpMethod == String.Empty) // Can't handle empty requests, not wasting a thread { byte[] buffer = GetHTML500(response); response.ContentLength64 = buffer.LongLength; response.Close(buffer, true); return; } response.KeepAlive = false; string requestMethod = request.HttpMethod; string uriString = request.RawUrl; int requestStartTick = Environment.TickCount; // Will be adjusted later on. int requestEndTick = requestStartTick; IStreamedRequestHandler requestHandler = null; try { System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US", true); string path = request.RawUrl; string handlerKey = GetHandlerKey(request.HttpMethod, path); byte[] buffer = null; if ((request.ContentType == "application/xml" || request.ContentType == "text/xml") && GetXmlRPCHandler(request.RawUrl) != null) { buffer = HandleXmlRpcRequests(req, resp); } else if (TryGetStreamHandler(handlerKey, out requestHandler)) { response.ContentType = requestHandler.ContentType; // Lets do this defaulting before in case handler has varying content type. buffer = requestHandler.Handle(path, request.InputStream, req, resp); } request.InputStream.Close(); try { if (buffer != null) { if (request.ProtocolVersion.Minor == 0) { //HTTP 1.0... no chunking response.ContentLength64 = buffer.Length; using (Stream stream = response.OutputStream) { HttpServerHandlerHelpers.WriteNonChunked(stream, buffer); } } else { response.SendChunked = true; using (Stream stream = response.OutputStream) { HttpServerHandlerHelpers.WriteChunked(stream, buffer); } } response.Close(); } else { response.Close(new byte[0], true); } } catch (Exception ex) { if (!(ex is HttpListenerException) || !HttpListenerManager.IGNORE_ERROR_CODES.Contains(((HttpListenerException)ex).ErrorCode)) { MainConsole.Instance.WarnFormat( "[BASE HTTP SERVER]: HandleRequest failed to write all data to the stream: {0}", ex.ToString()); } response.Abort(); } requestEndTick = Environment.TickCount; } catch (Exception e) { MainConsole.Instance.ErrorFormat("[BASE HTTP SERVER]: HandleRequest() threw {0} ", e.ToString()); response.Abort(); } finally { // Every month or so this will wrap and give bad numbers, not really a problem // since its just for reporting int tickdiff = requestEndTick - requestStartTick; if (tickdiff > 3000 && requestHandler != null) { MainConsole.Instance.InfoFormat( "[BASE HTTP SERVER]: Slow handling of {0} {1} took {2}ms", requestMethod, uriString, tickdiff); } else if (MainConsole.Instance.IsTraceEnabled) { MainConsole.Instance.TraceFormat( "[BASE HTTP SERVER]: Handling {0} {1} took {2}ms", requestMethod, uriString, tickdiff); } } } }
private static WopiRequest ParseRequest(HttpListenerRequest request) { WopiRequest requestData = new WopiRequest() { Type = RequestType.None, AccessToken = request.QueryString["access_token"], Id = "", LockId = request.Headers[WopiHeaders.Lock], OldLockId = request.Headers[WopiHeaders.OldLock] }; string requestPath = request.Url.AbsolutePath; string wopiPath = requestPath.Substring(WopiPath.Length); if (wopiPath.StartsWith(FilesRequestPath)) { string rawId = wopiPath.Substring(FilesRequestPath.Length); if (rawId.EndsWith(ContentsRequestPath)) { requestData.Id = rawId.Substring(0, rawId.Length - ContentsRequestPath.Length); if (request.HttpMethod == "GET") { requestData.Type = RequestType.GetFile; } if (request.HttpMethod == "POST") { requestData.Type = RequestType.PutFile; using (var memstream = new MemoryStream()) { memstream.Flush(); memstream.Position = 0; request.InputStream.CopyTo(memstream); requestData.FileData = memstream.ToArray(); } } } else { requestData.Id = rawId; if (request.HttpMethod == "GET") { requestData.Type = RequestType.CheckFileInfo; } else if (request.HttpMethod == "POST") { string wopiOverride = request.Headers[WopiHeaders.RequestType]; switch (wopiOverride) { case "PUT_RELATIVE": requestData.Type = RequestType.PutRelativeFile; if (request.Headers[WopiHeaders.RelativeTarget] != null) { requestData.RelativeTarget = request.Headers[WopiHeaders.RelativeTarget]; } if (request.Headers[WopiHeaders.SuggestedTarget] != null) { requestData.SuggestedTarget = request.Headers[WopiHeaders.SuggestedTarget]; } if (request.Headers[WopiHeaders.OverwriteRelativeTarget] != null) { requestData.OverwriteTarget = bool.Parse(request.Headers[WopiHeaders.OverwriteRelativeTarget]); } using (var memstream = new MemoryStream()) { memstream.Flush(); memstream.Position = 0; request.InputStream.CopyTo(memstream); requestData.FileData = memstream.ToArray(); } break; case "LOCK": if (request.Headers[WopiHeaders.OldLock] != null) { requestData.Type = RequestType.UnlockAndRelock; } else { requestData.Type = RequestType.Lock; } break; case "UNLOCK": requestData.Type = RequestType.Unlock; break; case "REFRESH_LOCK": requestData.Type = RequestType.RefreshLock; break; case "COBALT": requestData.Type = RequestType.ExecuteCobaltRequest; break; case "DELETE": requestData.Type = RequestType.DeleteFile; break; case "READ_SECURE_STORE": requestData.Type = RequestType.ReadSecureStore; break; case "GET_RESTRICTED_LINK": requestData.Type = RequestType.GetRestrictedLink; break; case "REVOKE_RESTRICTED_LINK": requestData.Type = RequestType.RevokeRestrictedLink; break; case "GET_LOCK": requestData.Type = RequestType.GetLock; break; } } } } else if (wopiPath.StartsWith(FoldersRequestPath)) { string rawId = wopiPath.Substring(FoldersRequestPath.Length); if (rawId.EndsWith(ChildrenRequestPath)) { requestData.Id = rawId.Substring(0, rawId.Length - ChildrenRequestPath.Length); requestData.Type = RequestType.EnumerateChildren; } else { requestData.Id = rawId; requestData.Type = RequestType.CheckFolderInfo; } } else { requestData.Type = RequestType.None; } return(requestData); }
public void InitTest() { lastRequest = null; }
private static void Main(string[] args) { //if HttpListener is not supported by the Framework if (!HttpListener.IsSupported) { Console.WriteLine("A more recent Windows version is required to use the HttpListener class."); return; } // Create a listener. HttpListener listener = new HttpListener(); // Add the prefixes. if (args.Length != 0) { foreach (string s in args) { listener.Prefixes.Add(s); // don't forget to authorize access to the TCP/IP addresses localhost:xxxx and localhost:yyyy // with netsh http add urlacl url=http://localhost:xxxx/ user="******" // and netsh http add urlacl url=http://localhost:yyyy/ user="******" // user="******" is language dependent, use user=Everyone in english } } else { Console.WriteLine("Syntax error: the call must contain at least one web server url as argument"); } listener.Start(); // get args foreach (string s in args) { Console.WriteLine("Listening for connections on " + s); } // Trap Ctrl-C on console to exit Console.CancelKeyPress += delegate { // call methods to close socket and exit listener.Stop(); listener.Close(); Environment.Exit(0); }; while (true) { // Note: The GetContext method blocks while waiting for a request. HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; string documentContents; using (Stream receiveStream = request.InputStream) { using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8)) { documentContents = readStream.ReadToEnd(); } } // get url Console.WriteLine($"Received request for {request.Url}"); //get url protocol Console.WriteLine(request.Url.Scheme); //get user in url Console.WriteLine(request.Url.UserInfo); //get host in url Console.WriteLine(request.Url.Host); //get port in url Console.WriteLine(request.Url.Port); //get path in url Console.WriteLine(request.Url.LocalPath); // parse path in url foreach (string str in request.Url.Segments) { Console.WriteLine(str); } //get params un url. After ? and between & Console.WriteLine(request.Url.Query); //parse params in url Console.WriteLine("param1 = " + HttpUtility.ParseQueryString(request.Url.Query).Get("param1")); Console.WriteLine("param2 = " + HttpUtility.ParseQueryString(request.Url.Query).Get("param2")); Console.WriteLine("param3 = " + HttpUtility.ParseQueryString(request.Url.Query).Get("param3")); Console.WriteLine("param4 = " + HttpUtility.ParseQueryString(request.Url.Query).Get("param4")); //################################################################################################## //generation dynamique de document string methodeName = request.Url.Segments[request.Url.Segments.Length - 1].ToLower(); MyMethods myMthd = new MyMethods(); Type type = typeof(MyMethods); MethodInfo method = type.GetMethod(methodeName); if (method != null) { string[] parametres = { HttpUtility.ParseQueryString(request.Url.Query).Get("param1"), HttpUtility.ParseQueryString(request.Url.Query).Get("param2") }; documentContents = (string)method.Invoke(myMthd, parametres); } else { Console.WriteLine("Le lien est incorecte"); } //################################################################################################## // Console.WriteLine(documentContents); // 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); // You must close the output stream. output.Close(); } // Httplistener neither stop ... But Ctrl-C do that ... // listener.Stop(); }
public override Task <string> ProcessRequest_Get(Player requestingPlayer, HttpListenerRequest request, string[] parameters) { return(Task.FromResult(String.Empty)); }
static void Test() { while (true) { HttpListenerContext context = null; lock (list) { if (list.Count > 0) { context = list[0]; list.RemoveAt(0); } } if (context != null) { HttpListenerRequest request = context.Request; Console.WriteLine("-------------->"); foreach (string key in request.QueryString.AllKeys) { Console.WriteLine(key + " = " + request.QueryString[key].ToString()); } if (request.HttpMethod == "POST") { string documentContents; using (Stream receiveStream = request.InputStream) { using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8)) { documentContents = readStream.ReadToEnd(); } } Console.WriteLine($"Recived request for {request.Url}"); Console.WriteLine(documentContents); Dictionary <string, string> postParams = new Dictionary <string, string>(); string[] rawParams = documentContents.Split('&'); foreach (string param in rawParams) { string[] kvPair = param.Split('='); string key = kvPair[0]; string value = HttpUtility.UrlDecode(kvPair[1]); postParams.Add(key, value); Console.WriteLine(key + " = " + value); } } string guid = Guid.NewGuid().ToString(); string cmd = request.QueryString["cmd"]; Save(guid, cmd); HttpListenerResponse response = context.Response; Stream output = response.OutputStream; string pathToRead = pathReadXMLResult + guid + ".xml"; int timeout = 8000; Console.WriteLine("start timeout " + DateTime.Now.ToString()); while (timeout > 0) { if (File.Exists(pathToRead)) { Read(pathToRead, output); Console.WriteLine("Ok"); File.Delete(pathToRead); break; } else { timeout -= 400; Console.WriteLine(DateTime.Now.TimeOfDay.ToString()); Thread.Sleep(50); } } Console.WriteLine("end timeout " + DateTime.Now.ToString()); try { output.Close(); } catch (Exception e) { Console.WriteLine(e.Message); } } //Console.WriteLine(DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss")); Thread.Sleep(10); } }
string GetTest2(HttpListenerRequest req) { return("this is get test 2"); }
public void ListenerCallback(IAsyncResult result) { try { _Listener.BeginGetContext(new AsyncCallback(ListenerCallback), _Listener); } catch { } HttpListener listener = (HttpListener)result.AsyncState; HttpListenerContext context = listener.EndGetContext(result); try { HttpListenerRequest request = context.Request; string sRequest = ""; using (StreamReader reader = new StreamReader(request.InputStream)) sRequest = reader.ReadToEnd(); string requestUri = System.Web.HttpUtility.UrlDecode(request.RawUrl.Substring(14).ToLower()); Log($"{context.Request.RemoteEndPoint.Address}: {request.RawUrl.Substring(14)}"); // This is really messy and will be tidied at some point Action action; if (requestUri.StartsWith("status")) { // This is a request for all known locations/statuses of clients action = (() => { SendStatus(context); }); } else if (requestUri.StartsWith("trackedcommanders")) { action = (() => { SendAllStatus(context); }); } else if (requestUri.StartsWith("racestatus")) { action = (() => { SendRaceStatus(requestUri, context, sRequest); }); } else if (requestUri.StartsWith("racemonitoring/")) { action = (() => { ReturnWebResource(requestUri, context); }); } else if (requestUri.StartsWith("startrace")) { action = (() => { StartRace(sRequest, context); }); } else if (requestUri.StartsWith("resurrectcommander")) { if (requestUri.Length > 19) { action = (() => { ResurrectCommander(System.Web.HttpUtility.UrlDecode(request.RawUrl).Substring(33), context); }); } else { action = (() => { WriteErrorResponse(context.Response, HttpStatusCode.NotFound); }); } } else if (requestUri.StartsWith("getactiveraces")) { action = (() => { try { StringBuilder activeRaces = new StringBuilder(); foreach (Guid guid in _races.Keys) { if (!_races[guid].Finished) { activeRaces.AppendLine($"{guid},{_races[guid].Name}"); } } WriteResponse(context, activeRaces.ToString()); } catch (Exception ex) { LogError($"GetActiveRaces: {ex.Message}"); WriteErrorResponse(context.Response, HttpStatusCode.InternalServerError); } }); } else if (requestUri.StartsWith("getrace")) { if (requestUri.Length > 8) { // Guid can be specified in the Url or in POST data. This one has something in the Url Guid raceGuid = Guid.Empty; Guid.TryParse(requestUri.Substring(8), out raceGuid); action = (() => { GetRace(raceGuid, context); }); } else { // No Guid in the URL, so check request content action = (() => { GetRace(sRequest, context); }); } } else if (requestUri.StartsWith("stoprace")) { if (requestUri.Length > 9) { // Guid can be specified in the Url or in POST data. This one has something in the Url Guid raceGuid = Guid.Empty; Guid.TryParse(requestUri.Substring(9), out raceGuid); action = (() => { StopRace(raceGuid, context); }); } else { // No Guid in the URL, so check request content action = (() => { StopRace(sRequest, context); }); } } else if (requestUri.StartsWith("getcommanderraceevents")) { if (requestUri.Length > 23) { // Guid can be specified in the Url or in POST data. This one has something in the Url try { string[] requestParams = System.Web.HttpUtility.UrlDecode(request.RawUrl).Substring(37).Split('/'); Guid raceGuid = Guid.Empty; Guid.TryParse(requestParams[0], out raceGuid); action = (() => { GetCommanderRaceEvents(raceGuid, requestParams[1], context); }); } catch { action = (() => { WriteErrorResponse(context.Response, HttpStatusCode.NotFound); }); } } else { action = (() => { GetCommanderRaceEvents(sRequest, context); }); } } else if (requestUri.StartsWith("getcommanderracestatus")) { if (requestUri.Length > 23) { // Guid can be specified in the Url or in POST data. This one has something in the Url try { string[] requestParams = System.Web.HttpUtility.UrlDecode(request.RawUrl).Substring(37).Split('/'); Guid raceGuid = Guid.Empty; Guid.TryParse(requestParams[0], out raceGuid); action = (() => { GetCommanderRaceStatus(raceGuid, requestParams[1], context); }); } catch { action = (() => { WriteErrorResponse(context.Response, HttpStatusCode.NotFound); }); } } else { action = (() => { GetCommanderRaceStatus(sRequest, context); }); } } else if (requestUri.StartsWith("getcommanderracereport")) { if (requestUri.Length > 23) { // Guid can be specified in the Url or in POST data. This one has something in the Url try { string[] requestParams = System.Web.HttpUtility.UrlDecode(request.RawUrl).Substring(37).Split('/'); Guid raceGuid = Guid.Empty; Guid.TryParse(requestParams[0], out raceGuid); action = (() => { GetCommanderRaceReport(raceGuid, requestParams[1], context); }); } catch { action = (() => { WriteErrorResponse(context.Response, HttpStatusCode.NotFound); }); } } else { action = (() => { GetCommanderRaceReport(sRequest, context); }); } } else if (requestUri.StartsWith("registercommander")) { action = (() => { WriteResponse(context, _commanderRegistration.RegisterCommander(sRequest)); }); } else if (requestUri.StartsWith("renamecommander")) { string[] renameArgs = sRequest.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); if (renameArgs.Length == 2) { action = (() => { WriteResponse(context, _commanderRegistration.UpdateCommanderName(renameArgs[0], renameArgs[1])); }); } else { action = (() => { WriteErrorResponse(context.Response, HttpStatusCode.BadRequest); }); } } else { action = (() => { WriteResponse(context, $"{Application.ProductName} v{Application.ProductVersion}"); }); } action(); } catch (Exception ex) { LogError($"ListenerCallback: {ex}"); Log($"Requested Url: {context.Request.RawUrl}"); } }
internal void Listen() { var db = new KptRepository(); var listener = new HttpListener(); listener.Prefixes.Add("http://*****:*****@"{ ""system"":""kpt""}"; try { if (method == "GET") { responseString = GetApi(db, req, cmd); } else if (method == "POST") { responseString = PostApi(db, req, cmd); } else if (method == "PUT") { responseString = PutApi(db, req, cmd); } else if (method == "DELETE") { responseString = DeleteApi(db, req, cmd); } else { Console.WriteLine("不明"); } res.StatusCode = 200; res.ContentType = " application/json; charset=utf-8"; byte[] content = System.Text.Encoding.UTF8.GetBytes(responseString); res.ContentLength64 = content.Length; res.OutputStream.Write(content, 0, content.Length); } catch (Exception ex) { res.StatusCode = 500; // 404 でも良いのだがここは雑に 500 にまとめておく byte[] content = Encoding.UTF8.GetBytes(ex.Message); res.OutputStream.Write(content, 0, content.Length); content = Encoding.UTF8.GetBytes("\n"); res.OutputStream.Write(content, 0, content.Length); content = Encoding.UTF8.GetBytes(ex.StackTrace); res.OutputStream.Write(content, 0, content.Length); } res.Close(); } }
private Task _listen() { return(Task.Factory.StartNew(() => { try { while (IsListening) { HttpListenerContext ctx = _listener.GetContext(); HttpListenerRequest req = ctx.Request; HttpListenerResponse resp = ctx.Response; try { string accesslog = DateTime.Now.ToString("o"); accesslog += "\t" + string.Format("Request #: {0}", ++_requestCount); accesslog += "\t" + req.Url.ToString(); accesslog += "\t" + req.HttpMethod; accesslog += "\t" + req.UserHostAddress; accesslog += "\t" + req.UserAgent; string origin = _getOrigin(req); accesslog += "\t" + origin; bool forbidden = false; if (config.URL == origin || config.allowedDomains.Contains(origin)) { resp.AppendHeader("Access-Control-Allow-Origin", origin); } else { if (req.Url.AbsolutePath == "/permissions" && req.HttpMethod == "GET") { resp.AppendHeader("Access-Control-Allow-Origin", origin); } else { resp.AppendHeader("Access-Control-Allow-Origin", config.URL); forbidden = true; } } if (req.HttpMethod == "OPTIONS") { resp.AddHeader("Access-Control-Allow-Headers", "*"); resp.StatusCode = (int)HttpStatusCode.OK; resp.StatusDescription = "OK"; resp.Close(); } else { if (forbidden) { accesslog += "\tfailed\tsame origin"; ServerConfig.appendLog(accesslog); responseForbidden(resp); } else { ResponseCode respCode = ResponseCode.OK; if (req.Url.AbsolutePath == "/") { respCode = _home.handle(req, resp, accesslog); } else if (req.Url.AbsolutePath == "/permissions") { respCode = _permissions.handle(req, resp, accesslog, origin); } else if (req.Url.AbsolutePath == "/printers") { respCode = _printers.handle(req, resp, accesslog); } else if (req.Url.AbsolutePath == "/settings") { respCode = _settings.handle(req, resp, accesslog); } else { respCode = ResponseCode.NotFound; } switch (respCode) { case ResponseCode.NotFound: accesslog += "\tfailed\tnot found"; ServerConfig.appendLog(accesslog); resp.StatusCode = (int)HttpStatusCode.NotFound; resp.StatusDescription = "NOT FOUND"; resp.Close(); break; case ResponseCode.Forbidden: responseForbidden(resp); break; } } } } catch (Exception e) { ServerConfig.appendLog("Error: " + e.Message + "\n" + e.StackTrace); resp.StatusCode = (int)HttpStatusCode.InternalServerError; resp.StatusDescription = "INTERNAL SERVER ERROR"; resp.Close(); } } } catch (Exception e) { if (!(e is HttpListenerException && (e as HttpListenerException).ErrorCode == 995)) { ServerConfig.appendLog(e.GetType().Name + ": " + e.Message + "\n" + e.StackTrace); } return false; } return true; })); }
public override void OnGet(HttpListenerRequest request, HttpListenerResponse response) { ResponseFactory.GenerateResponse(response, "{\"status\":" + CoreState.SettingsInstance.IsFirstLaunch.ToString().ToLower() + "}"); }
private AuthenticationSchemes SelectAnonymousScheme(HttpListenerRequest request) => AuthenticationSchemes.Anonymous;
private void RunServer(object unusedState) { var prefixes = new string[] { "http://*/" }; if (prefixes == null || prefixes.Length == 0) { throw new ArgumentException("prefixes"); } // Create a listener. HttpListener listener = new HttpListener(); // Add the prefixes. foreach (string s in prefixes) { listener.Prefixes.Add(s); } listener.Start(); Log_ThreadSafe("Listening..."); // Note: The GetContext method blocks while waiting for a request. while (true) { HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; try { if (request.RawUrl.StartsWith("/updateCheck?")) { if ((request.RawUrl.ToLowerInvariant().Contains("requestIsFromService=true".ToLowerInvariant()) && !chkboxService.Checked) || (request.RawUrl.ToLowerInvariant().Contains("requestIsFromService=false".ToLowerInvariant()) && !chkboxClientApp.Checked)) { context.Response.ContentLength64 = 0; context.Response.OutputStream.Close(); Log_ThreadSafe("Turned down update request for " + request.RawUrl); } else { var buildNumber = GetUrlParameter(request.RawUrl, "build"); var clientGuid = GetUrlParameter(request.RawUrl, "clientGuid"); if (!m_clientGuidsSeen.Contains(clientGuid)) { var numUniqueClientsLeftToUpdate = (int)txtNumUniqueClientUpdatesRemaining.Invoke( new IntDelegate(GetNumUniqueClientUpdatesRemaining_ThreadUnsafe)); if (numUniqueClientsLeftToUpdate == 0) { // no more! context.Response.ContentLength64 = 0; context.Response.OutputStream.Close(); Log_ThreadSafe("Turned down update request because no more update counts available"); continue; } txtNumUniqueClientUpdatesRemaining.Invoke(new VoidDelegate(DecrementNumUniqueClientUpdatesRemaining_ThreadSafe)); m_clientGuidsSeen.Add(clientGuid); CountNewUniqueClientGuid_ThreadSafe(); } if (txtBuildNumber.Text.Length > 0 && int.Parse(txtBuildNumber.Text) <= int.Parse(buildNumber)) { context.Response.ContentLength64 = 0; context.Response.OutputStream.Close(); Log_ThreadSafe("Turned down update request due to lower build number, for " + request.RawUrl); continue; } // we're actually going to send the update command! HttpListenerResponse response = context.Response; // Construct a response. string responseString = File.ReadAllText((string)txtXml.Invoke(new SimpleDelegate(delegate() { return(txtXml.Text); }))); 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(); Log_ThreadSafe(string.Format("Recieved request for ({0}/{1}) {2} ... sent response from {3}", buildNumber, clientGuid, request.RawUrl, txtXml.Text)); } } else { // Obtain a response object. HttpListenerResponse response = context.Response; // Construct a response. var filePath = (string)txtExe.Invoke(new SimpleDelegate(delegate() { return(txtExe.Text); })); if (File.Exists(filePath)) { byte[] buffer = File.ReadAllBytes(filePath); // 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(); Log_ThreadSafe("Recieved request for " + request.RawUrl + "... sent response from " + txtExe.Text); } else { Log_ThreadSafe("Recieved request for " + request.RawUrl + "... rejecting..."); context.Response.ContentLength64 = 0; context.Response.OutputStream.Close(); } } } catch (Exception e) { Log_ThreadSafe(string.Format("Exception {0} on URL {1}", e.Message, request.RawUrl)); } } listener.Stop(); }
internal static async Task <HttpListenerWebSocketContext> AcceptWebSocketAsyncCore(HttpListenerContext context, string subProtocol, int receiveBufferSize, TimeSpan keepAliveInterval, ArraySegment <byte>?internalBuffer = null) { ValidateOptions(subProtocol, receiveBufferSize, MinSendBufferSize, keepAliveInterval); // get property will create a new response if one doesn't exist. HttpListenerResponse response = context.Response; HttpListenerRequest request = context.Request; ValidateWebSocketHeaders(context); string secWebSocketVersion = request.Headers[HttpKnownHeaderNames.SecWebSocketVersion]; // Optional for non-browser client string origin = request.Headers[HttpKnownHeaderNames.Origin]; string[] secWebSocketProtocols = null; string outgoingSecWebSocketProtocolString; bool shouldSendSecWebSocketProtocolHeader = ProcessWebSocketProtocolHeader( request.Headers[HttpKnownHeaderNames.SecWebSocketProtocol], subProtocol, out outgoingSecWebSocketProtocolString); if (shouldSendSecWebSocketProtocolHeader) { secWebSocketProtocols = new string[] { outgoingSecWebSocketProtocolString }; response.Headers.Add(HttpKnownHeaderNames.SecWebSocketProtocol, outgoingSecWebSocketProtocolString); } // negotiate the websocket key return value string secWebSocketKey = request.Headers[HttpKnownHeaderNames.SecWebSocketKey]; string secWebSocketAccept = HttpWebSocket.GetSecWebSocketAcceptString(secWebSocketKey); response.Headers.Add(HttpKnownHeaderNames.Connection, HttpKnownHeaderNames.Upgrade); response.Headers.Add(HttpKnownHeaderNames.Upgrade, WebSocketUpgradeToken); response.Headers.Add(HttpKnownHeaderNames.SecWebSocketAccept, secWebSocketAccept); response.StatusCode = (int)HttpStatusCode.SwitchingProtocols; // HTTP 101 response.StatusDescription = HttpStatusDescription.Get(HttpStatusCode.SwitchingProtocols); HttpResponseStream responseStream = response.OutputStream as HttpResponseStream; // Send websocket handshake headers await responseStream.WriteWebSocketHandshakeHeadersAsync().ConfigureAwait(false); const int MinBufferSize = 14; // from ManagedWebSocket.MaxMessageHeaderLength Memory <byte> buffer = internalBuffer.GetValueOrDefault().Count >= MinBufferSize?internalBuffer.GetValueOrDefault() : // use provided buffer if it's big enough receiveBufferSize >= MinBufferSize ? new byte[receiveBufferSize] : // or use provided size if it's big enough Memory <byte> .Empty; // or use the default WebSocket webSocket = WebSocket.CreateFromStream(context.Connection.ConnectedStream, isServer: true, subProtocol, keepAliveInterval, buffer); HttpListenerWebSocketContext webSocketContext = new HttpListenerWebSocketContext( request.Url, request.Headers, request.Cookies, context.User, request.IsAuthenticated, request.IsLocal, request.IsSecureConnection, origin, secWebSocketProtocols != null ? secWebSocketProtocols : Array.Empty <string>(), secWebSocketVersion, secWebSocketKey, webSocket); return(webSocketContext); }
private static void Main(string[] args) { Mymethods mymethods = new Mymethods(); if (!HttpListener.IsSupported) { Console.WriteLine("A more recent Windows version is required to use the HttpListener class."); return; } HttpListener listener = new HttpListener(); if (args.Length != 0) { foreach (string s in args) { listener.Prefixes.Add(s); } } else { Console.WriteLine("Syntax error: the call must contain at least one web server url as argument"); } listener.Start(); foreach (string s in args) { Console.WriteLine("Listening for connections on " + s); } Console.CancelKeyPress += delegate { listener.Stop(); listener.Close(); Environment.Exit(0); }; while (true) { HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; string documentContents; using (Stream receiveStream = request.InputStream) { using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8)) { documentContents = readStream.ReadToEnd(); } } // get url Console.WriteLine($"Received request for {request.Url}"); string result = ""; //On récupère le nom de la méthode à appeler. string methodName = request.Url.Segments[request.Url.Segments.Length - 1]; //On essaye d'appeller la méthode. try { Type type = typeof(Mymethods); MethodInfo method = type.GetMethod(methodName);//Récupère la méthode correpondante au nom récupéré. //Appel de la méthode et on récupère ce qui est retourné. result = (string)method.Invoke(mymethods, new Object[] { HttpUtility.ParseQueryString(request.Url.Query).Get("param1"), HttpUtility.ParseQueryString(request.Url.Query).Get("param2") }); } // On tombe dans un cas d'erreur quand celle-ci n'existe pas catch (NullReferenceException e) { Console.Write("Method not found"); } Console.WriteLine(documentContents); //Construction d'une réponse pour la requête. HttpListenerResponse response = context.Response; //Retourne la page web correspondante. byte[] buffer = System.Text.Encoding.UTF8.GetBytes(result); response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); output.Close(); } }
public HttpListenerRequestWrapper( string operationName, HttpListenerRequest request) { this.OperationName = operationName; this.request = request; }
public virtual void Handle(HttpListenerRequest request, HttpListenerResponse response) { }
private AuthenticationSchemes SelectAnonymousScheme(HttpListenerRequest request) { return(AuthenticationSchemes.Anonymous); }
public BypassContext(HttpListenerRequest request, HttpListenerResponse response, HttpWebRequest cloudRequest) { this.request = request; this.response = response; this.cloudRequest = cloudRequest; }
public void HandlePost(HttpListenerRequest request, HttpListenerResponse response, Server.RequestData data) { response.StatusCode = 404; response.WriteResponse("404 Page Not Found"); }
public abstract void Process(HttpListenerRequest request, HttpListenerResponse response);
private static void sendFile(HttpListenerRequest request,HttpListenerResponse response) { String file = VolumeInfo.GetVolumes()[0].RootDirectory + formatUrl(request.RawUrl); FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read); byte[] page = new byte[1024]; while (fs.Read(page, 0, 1024) > 0) { response.OutputStream.Write(page, 0, page.Length); Array.Clear(page, 0, 1024); Debug.GC(true); } fs.Close(); }
public static T ResolveService <T>(HttpListenerRequest httpReq, HttpListenerResponse httpRes) where T : class, IRequiresRequestContext { return(ResolveService <T>(httpReq.ToRequest(), httpRes.ToResponse())); }
public override bool CanProcess(HttpListenerRequest request) { return(request.Url.PathAndQuery.StartsWith(Path, StringComparison.InvariantCultureIgnoreCase)); }
static void StartServer() { httpListener.AuthenticationSchemes = AuthenticationSchemes.Anonymous; var prefixes = new List <string>() { "http://*:8082/ser/" }; foreach (string prefix in prefixes) { httpListener.Prefixes.Add(prefix); } Console.WriteLine("Server start on *:8082/ser/"); httpListener.Start(); new Thread(new ThreadStart(delegate { while (true) { HttpListenerContext context = httpListener.GetContext(); HttpListenerRequest request = context.Request; NameValueCollection nv = request.QueryString; string res = ""; string cmd = getValueFromNV(nv, "cmd"); if (null == cmd) { res = "http Service Start ,but unknown cmd , please invoke like this ,ReadCard : http://localhost:8082/ser?cmd=read&Stores_Number=316091 ,MakeCard : http://localhost:8082/ser?cmd=make&Stores_Number=316091&User_Name=Lish&Room_Num=10301&Control_Code=0100&Begin_Time=2019-03-26%2022:34:00&End_Time=2019-03-26%2022:34:00"; } //http://localhost:8082/ser?cmd=read&Stores_Number=316091 else if (cmd.ToUpper().StartsWith("READ")) { if (0 == h.Initialize()) { res = read(getValueFromNV(nv, "Stores_Number")); } else { res = INITIALIZEERRORSTR; } } //http://localhost:8082/ser?cmd=make&Stores_Number=316091&User_Name=Lish&Room_Num=10301&Control_Code=0100&Begin_Time=2019-03-26%2022:34:00&End_Time=2019-03-26%2022:34:00 else if (cmd.ToUpper().StartsWith("MAKE")) { if (0 == h.Initialize()) { string Stores_Number = getValueFromNV(nv, "Stores_Number"); string User_Name = getValueFromNV(nv, "User_Name"); string Room_Num = getValueFromNV(nv, "Room_Num"); string Control_Code = getValueFromNV(nv, "Control_Code"); string Begin_Time = getValueFromNV(nv, "Begin_Time"); string End_Time = getValueFromNV(nv, "End_Time"); res = make(Stores_Number, User_Name, Room_Num, Control_Code, Begin_Time, End_Time); } else { res = INITIALIZEERRORSTR; } } else { res = "false|unknown cmd"; } HttpListenerResponse response = context.Response; response.StatusCode = 200; response.ContentType = "text/html"; WebHeaderCollection headers = new WebHeaderCollection(); headers.Set("hello", ""); response.Headers = headers; using (StreamWriter writer = new StreamWriter(response.OutputStream)) { writer.WriteLine(res); } context.Response.Close(); } })).Start(); }
public static string SendResponse(HttpListenerRequest request) { return string.Format("<HTML><BODY>My web page.<br>{0}</BODY></HTML>", DateTime.Now); }
void DumpRequest (HttpListenerRequest request, StringBuilder sb) { DumpObject (request, sb); }