protected override IEnumerator OnRequest(HttpListenerContext context) { Debug.Log ("Some Random String"); HttpListenerResponse response = context.Response; Stream stream = response.OutputStream; response.ContentType = "application/octet-stream"; byte[] data = unityWebPackage.bytes; int i = 0; int count = data.Length; while(i < count) { if (i != 0) yield return null; int writeLength = Math.Min((int)writeStaggerCount, count - i); stream.Write(data, i, writeLength); i += writeLength; } }
public IEnumerator ProcessRequest(HttpListenerContext context, System.Action<bool> isMatch) { string url = context.Request.RawUrl; //Debug.Log (url); bool match = false; foreach(Regex regex in regexList) { if (regex.Match(url).Success) { match = true; break; } } if (!match) { isMatch(false); yield break; } IEnumerator e = OnRequest(context); do { yield return null; } while (e.MoveNext()); isMatch(true); }
public void Handle(HttpListenerContext context) { HttpListenerResponse response = context.Response; // Get device data string id = context.Request.QueryString["id"]; Device device = _deviceManager.FindDeviceByID(id); // Create response string message = "{\"Version\":\"2.0.1\", \"Auth\": \""; response.StatusCode = (int)HttpStatusCode.OK; if (device != null || !_deviceManager.AuthenticationEnabled) { message += "OK\"}"; } else { message += "DENIED\"}"; } // Fill in response body byte[] messageBytes = Encoding.Default.GetBytes(message); response.OutputStream.Write(messageBytes, 0, messageBytes.Length); response.ContentType = "application/json"; // Send the HTTP response to the client response.Close(); }
static void ResponseHandler (HttpListenerContext httpContext) { byte [] buffer = Encoding.ASCII.GetBytes ("hello world"); httpContext.Response.StatusCode = 200; httpContext.Response.OutputStream.Write (buffer, 0, buffer.Length); httpContext.Response.Close (); }
protected override IEnumerator OnRequest(HttpListenerContext context) { Debug.Log("Hello:" + context.Request.UserHostAddress); string html = htmlPage.text; foreach(HtmlKeyValue pair in substitutions) { html = html.Replace(string.Format("${0}$", pair.Key), pair.Value); } html = ModifyHtml(html); byte[] data = Encoding.ASCII.GetBytes(html); yield return null; HttpListenerResponse response = context.Response; response.ContentType = "text/html"; Stream responseStream = response.OutputStream; int count = data.Length; int i = 0; while(i < count) { if (i != 0) yield return null; int writeLength = Math.Min((int)writeStaggerCount, count - i); responseStream.Write(data, i, writeLength); i += writeLength; } }
internal HttpListenerRequest (HttpListenerContext context) { this.context = context; headers = new WebHeaderCollection (); input_stream = Stream.Null; version = HttpVersion.Version10; }
public HttpListenerHost(HttpListenerContext context, string serviceUri) { this.httpListenerContext = context; // retrieve request information from HttpListenerContext HttpListenerRequest contextRequest = context.Request; this.AbsoluteRequestUri = new Uri(contextRequest.Url.AbsoluteUri); this.AbsoluteServiceUri = new Uri(serviceUri); this.RequestPathInfo = this.AbsoluteRequestUri.MakeRelativeUri(this.AbsoluteServiceUri).ToString(); // retrieve request headers this.RequestAccept = contextRequest.Headers[HttpAccept]; this.RequestAcceptCharSet = contextRequest.Headers[HttpAcceptCharset]; this.RequestIfMatch = contextRequest.Headers[HttpIfMatch]; this.RequestIfNoneMatch = contextRequest.Headers[HttpIfNoneMatch]; this.RequestMaxVersion = contextRequest.Headers[HttpMaxDataServiceVersion]; this.RequestVersion = contextRequest.Headers[HttpDataServiceVersion]; this.RequestContentType = contextRequest.ContentType; this.RequestHeaders = new WebHeaderCollection(); foreach (string header in contextRequest.Headers.AllKeys) this.RequestHeaders.Add(header, contextRequest.Headers.Get(header)); this.QueryStringValues = new Dictionary<string, string>(); string queryString = this.AbsoluteRequestUri.Query; var parsedValues = HttpUtility.ParseQueryString(queryString); foreach (string option in parsedValues.AllKeys) this.QueryStringValues.Add(option, parsedValues.Get(option)); processExceptionCalled = false; }
public bool GetPeople(WebServer server, HttpListenerContext context) { try { // read the last segment var lastSegment = context.Request.Url.Segments.Last(); // if it ends with a / means we need to list people if (lastSegment.EndsWith("/")) return context.JsonResponse(_dbContext.People.SelectAll()); // if it ends with "first" means we need to show first record of people if (lastSegment.EndsWith("first")) return context.JsonResponse(_dbContext.People.SelectAll().First()); // otherwise, we need to parse the key and respond with the entity accordingly int key = 0; if (int.TryParse(lastSegment, out key)) { var single = _dbContext.People.Single(key); if (single != null) return context.JsonResponse(single); } throw new KeyNotFoundException("Key Not Found: " + lastSegment); } catch (Exception ex) { // here the error handler will respond with a generic 500 HTTP code a JSON-encoded object // with error info. You will need to handle HTTP status codes correctly depending on the situation. // For example, for keys that are not found, ou will need to respond with a 404 status code. return HandleError(context, ex, (int)System.Net.HttpStatusCode.InternalServerError); } }
public bool GetPeople(WebServer server, HttpListenerContext context) { try { // read the last segment var lastSegment = context.Request.Url.Segments.Last(); // if it ends with a / means we need to list people if (lastSegment.EndsWith("/")) return context.JsonResponse(PeopleRepository.Database); // otherwise, we need to parse the key and respond with the entity accordingly int key; if (int.TryParse(lastSegment, out key) && PeopleRepository.Database.Any(p => p.Key == key)) { return context.JsonResponse(PeopleRepository.Database.FirstOrDefault(p => p.Key == key)); } throw new KeyNotFoundException("Key Not Found: " + lastSegment); } catch (Exception ex) { context.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; return context.JsonResponse(ex); } }
/// <summary> /// Request handler function. Overriden from RequestHandler class /// </summary> /// <param name="context">Request context</param> public override void HandleReqest(HttpListenerContext context) { _content.Append(TemplateText); if (context.Request.HttpMethod == "GET") { if (GetHandler != null) { GetHandler(this, new HTTPEventArgs(EmbeddedHttpServer.GetFileName(context.Request.RawUrl), context.Request.QueryString)); } } if (TemplateTags != null) { foreach (var keyvaluepair in TemplateTags) { var toreplace = "{{" + keyvaluepair.Key + "}}"; _content.Replace(toreplace, keyvaluepair.Value.ToString()); } } MarkdownSharp.Markdown md = new MarkdownSharp.Markdown(); var output = Encoding.UTF8.GetBytes(BaseHTMLTemplate.Replace("{{md}}", md.Transform(_content.ToString()))); context.Response.ContentType = "text/html"; context.Response.ContentLength64 = output.Length; context.Response.OutputStream.Write(output, 0, output.Length); }
internal HttpListenerWebSocketContext( HttpListenerContext context, Logger logger) { _context = context; _stream = WsStream.CreateServerStream (context); _websocket = new WebSocket (this, logger ?? new Logger ()); }
internal HttpListenerRequest(HttpListenerContext context) { _context = context; _contentLength = -1; _headers = new WebHeaderCollection (); _identifier = Guid.NewGuid (); _version = HttpVersion.Version10; }
internal HttpListenerRequest(HttpListenerContext context) { this.context = context; headers = new WebHeaderCollection(); version = HttpVersion.Version10; }
public ChunkedInputStream ( HttpListenerContext context, Stream stream, byte [] buffer, int offset, int length) : base (stream, buffer, offset, length) { this.context = context; WebHeaderCollection coll = (WebHeaderCollection) context.Request.Headers; decoder = new ChunkStream (coll); }
private void InvokeHandler(IHttpRequestHandler handler, HttpListenerContext context) { if (handler == null) return; Console.WriteLine("Request being handled"); HandleHttpRequestCommand command = new HandleHttpRequestCommand(handler, context); Thread commandThread = new Thread(command.Execute); commandThread.Start(); }
private void InvokeHandler(HttpRequestHandler handler, HttpListenerContext context) { // Start a new thread to invoke the handler to process the HTTP request HandleHttpRequestCommand handleHttpRequestCommand = new HandleHttpRequestCommand(handler, context); Thread handleHttpRequestThread = new Thread(handleHttpRequestCommand.Execute); handleHttpRequestThread.Start(); }
public void Handle(HttpListenerContext context) { HttpListenerResponse resp = context.Response; string message = "you just sent me a message"; byte[] bytes = Encoding.Default.GetBytes(message); resp.OutputStream.Write(bytes, 0, bytes.Length); resp.Close(); Console.WriteLine("handled diff sync request"); }
public void Handle(HttpListenerContext context) { HttpListenerResponse serverResponse = context.Response; // Indicate the failure as a 404 not found serverResponse.StatusCode = (int) HttpStatusCode.BadRequest; // Send the HTTP response to the client serverResponse.Close(); }
public void Handle(HttpListenerContext context) { HttpListenerResponse response = context.Response; // Get query data string type = context.Request.QueryString["type"]; string names = context.Request.QueryString["name"]; string id = context.Request.QueryString["id"]; string message = ""; // Authenticate bool authorized = true; DeviceManager dm = _parent.GetDeviceManager(); if (dm.FindDeviceByID(id) == null && dm.AuthenticationEnabled) { response.StatusCode = (int) HttpStatusCode.Unauthorized; message = "401 Unauthorized"; authorized = false; } // Check what kind of data is requested if (type != null && authorized) { response.StatusCode = (int)HttpStatusCode.OK; switch (type) { case "cpu": message = HandleCPU(names); break; case "gpu": message = HandleGPU(names); break; case "fs": message = HandleFilesystems(); break; case "processes": message = HandleProcesses(context.Request.QueryString["sort"]); break; case "system": message = HandleSystem(names); break; case "disks": message = HandleDisks(); break; case "listdev": message = HandleListDevices(); break; case "history": message = HandleHistory(); break; case "historyfile": message = HandleHistoryFile(context.Request.QueryString["file"]); break; case "historylist": message = HandleHistoryList(context.Request.QueryString["sort"]); break; case "overview": message = HandleOverview(); break; case "addnotif": message = HandleAddNotification(context.Request.QueryString["id"], context.Request.QueryString["name"], context.Request.QueryString["ntype"], context.Request.QueryString["condition"], context.Request.QueryString["value"], context.Request.QueryString["ringonce"]); break; case "listnotif": message = HandleGetNotifications(context.Request.QueryString["id"]); break; case "remnotif": message = HandleRemoveNotification(context.Request.QueryString["id"], context.Request.QueryString["index"]); break; case "testnotif": message = HandleTestNotification(context.Request.QueryString["id"]); break; } } else if (authorized) { response.StatusCode = (int) HttpStatusCode.BadRequest; message = "400 Bad request"; } // Send the HTTP response to the client response.ContentType = "application/json"; byte[] messageBytes = Encoding.Default.GetBytes(message); response.OutputStream.Write(messageBytes, 0, messageBytes.Length); response.Close(); }
protected override IEnumerator OnRequest(HttpListenerContext context) { HttpListenerRequest request = context.Request; TextAsset textItem; byte[] data = new byte[0]; string url = request.RawUrl; //Debug.Log ("RAW: " + url); string subFolder = ""; string[] directories = url.Split ('/'); for (int s = urlRegexList [0].Split('/').Length - 1; s < directories.Length - 1; s++) subFolder += directories [s]+"/"; string item = url.Substring(url.LastIndexOf('/') + 1); //Debug.Log ("ITEM: " + item); string itemName = item.Substring(0, item.IndexOf('.')); //Debug.Log ("NAME: " + itemName); string path = string.Format ("{0}{1}", subFolder, itemName); Debug.Log ("PATH: " + path); try { //Debug.Log (Resources.Load (path).GetType ().ToString ()); textItem = Resources.Load(path) as TextAsset; data = textItem.bytes; } catch (Exception e){ Debug.Log("Cannot produce asset at path: " + path + " with Exception: " + e.Message); } yield return null; /// HttpListenerResponse response = context.Response; response.ContentType = "text/html"; Stream responseStream = response.OutputStream; int count = data.Length; int i = 0; while (i < count) { if (i != 0) yield return null; int writeLength = Math.Min((int)writeStaggerCount, count - i); responseStream.Write(data, i, writeLength); i += writeLength; } }
public static HttpListenerResponse SendResponse(HttpListenerContext ctx) { HttpListenerRequest request = ctx.Request; HttpListenerResponse response = ctx.Response; response.StatusCode = (int)HttpStatusCode.OK; response.ContentType = "application/xml"; var twiml = new Twilio.TwiML.TwilioResponse(); twiml.Enqueue (new { workflowSid = "WW0123456789abcdef0123456789abcdef", waitUrl = "/hold_music.php", action = "/post_bridge_survey.php"}, "{\"account_number\":\"12345abcdef\"}"); response.StatusDescription = twiml.ToString(); return response; }
public static HttpListenerResponse SendResponse(HttpListenerContext ctx) { HttpListenerRequest request = ctx.Request; HttpListenerResponse response = ctx.Response; response.StatusCode = (int)HttpStatusCode.OK; response.ContentType = "application/xml"; var twiml = new Twilio.TwiML.TwilioResponse(); twiml.Enqueue (new { workflowSid = "WW0123456789abcdef0123456789abcdef" }); response.StatusDescription = twiml.ToString(); return response; }
public void Handle(HttpListenerContext context) { HttpListenerResponse response = context.Response; // Check if we need to ask the user for registration Result result; if (context.Request.QueryString["ask"] != null && context.Request.QueryString["ask"].ToLower() == "true") { result = Result.AskUser; } else { result = Result.DoNothing; } // Create device object string name = context.Request.QueryString["name"]; string id = context.Request.QueryString["id"]; string gcm = context.Request.QueryString["gcm"]; // Create response string message = "{\"Version\":\"2.0.1\","; // Register device if it's not ready Device possibleDevice = _deviceManager.FindDeviceByID(id); if (_deviceManager.AuthenticationEnabled) { if (possibleDevice == null) { message += "\"Status\":\"WAITING\"}"; } else { result = Result.DoNothing; if (possibleDevice.Allowed == true) message += "\"Status\":\"ALLOWED\"}"; else message += "\"Status\":\"DENIED\"}"; } } else { message += "\"Status\":\"ALLOWED\"}"; if (possibleDevice == null) result = Result.SaveDevice; else result = Result.DoNothing; } // Fill in response body byte[] messageBytes = Encoding.Default.GetBytes(message); response.OutputStream.Write(messageBytes, 0, messageBytes.Length); response.ContentType = "application/json"; response.StatusCode = (int)HttpStatusCode.OK; // Send the HTTP response to the client response.Close(); // Decide what to do with this device switch (result) { case Result.AskUser: AskForRegistration(name, id, gcm); break; case Result.SaveDevice: _deviceManager.AddDevice(new Device(name, id, gcm, true)); _deviceManager.SaveData(); break; } }
public HttpListenerWorkerRequest( HttpListenerContext context, string vdir, string pdir) { if (null == context) throw new ArgumentNullException("context"); if (null == vdir || vdir.Equals("")) throw new ArgumentException("vdir"); if (null == pdir || pdir.Equals("")) throw new ArgumentException("pdir"); _context = context; _virtualDir = vdir; _physicalDir = pdir; }
protected override IEnumerator OnRequest(HttpListenerContext context) { HttpListenerRequest request = context.Request; TextAsset textItem = new TextAsset (); string url = request.RawUrl; Debug.Log ("RAW: " + url); string subFolder = ""; string[] directories = url.Split ('/'); for (int s = 3; s< directories.Length - 1; s++) { subFolder += directories [s]+"/"; } string item = url.Substring(url.LastIndexOf('/') + 1); Debug.Log ("ITEM: " + item); string itemName = item.Substring(0, item.IndexOf('.')); Debug.Log ("NAME: " + itemName); // "HesitNight/sprites -> "Resources/www/sprites/asset" string path = string.Format ("www/Website/{0}{1}", subFolder, itemName); Debug.Log ("PATH: " + path); textItem = Resources.Load(path) as TextAsset; yield return null; /// HttpListenerResponse response = context.Response; byte[] data = textItem.bytes; response.ContentType = "text/html"; Stream responseStream = response.OutputStream; int count = data.Length; int i = 0; while(i < count) { if (i != 0) yield return null; int writeLength = Math.Min((int)writeStaggerCount, count - i); responseStream.Write(data, i, writeLength); i += writeLength; } }
public bool PostPeople(WebServer server, HttpListenerContext context) { try { var content = context.ParseJson<Person>(); return context.JsonResponse(content); } catch (Exception ex) { context.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; return context.JsonResponse(ex); } }
public void Handle(HttpListenerContext context) { HttpListenerResponse response = context.Response; // Create response string message = "{\"AuthEnabled\":\"" + _deviceManager.AuthenticationEnabled.ToString() + "\"}"; response.StatusCode = (int)HttpStatusCode.OK; // Fill in response body byte[] messageBytes = Encoding.Default.GetBytes(message); response.OutputStream.Write(messageBytes, 0, messageBytes.Length); response.ContentType = "application/json"; // Send the HTTP response to the client response.Close(); }
public bool GetPerson(WebServer server, HttpListenerContext context, DateTime date) { try { if (PeopleRepository.Database.Any(p => p.DoB == date)) { return context.JsonResponse(PeopleRepository.Database.FirstOrDefault(p => p.DoB == date)); } throw new KeyNotFoundException("Key Not Found: " + date); } catch (Exception ex) { context.Response.StatusCode = errorCode; return context.JsonResponse(ex); } }
public void HandleContext(HttpListenerContext context) { Console.WriteLine("Request recieved"); HttpListenerRequest request = context.Request; string requestHandlerName = request.Url.AbsolutePath; IHttpRequestHandler handler; if (handlerDictionary.ContainsKey(requestHandlerName)) { handler = handlerDictionary[requestHandlerName]; } else { handler = null; Console.WriteLine("invalid request"); } this.InvokeHandler(handler, context); }
public static HttpListenerResponse SendResponse(HttpListenerContext ctx) { HttpListenerRequest request = ctx.Request; HttpListenerResponse response = ctx.Response; response.StatusCode = (int)HttpStatusCode.OK; response.ContentType = "application/xml"; var twiml = new Twilio.TwiML.TwilioResponse(); var task = new Task("{\"account_number\":\"12345abcdef\"}", new {priority = "5", timeout = "200"}); twiml.EnqueueTask (new { workflowSid = "WW0123456789abcdef0123456789abcdef" }, task); // alternatively twiml.Enqueue (new { workflowSid = "WW0123456789abcdef0123456789abcdef" }, "{\"account_number\":\"12345abcdef\"}", new {priority = "5", timeout = "200"}); response.StatusDescription = twiml.ToString(); return response; }
public IndexPage(HttpListenerContext context) { _context = context; _responseText = ReadAllText(@"view\index.html"); }
//### Accepting WebSocket connections // Calling `AcceptWebSocketAsync` on the `HttpListenerContext` will accept the WebSocket connection, sending the required 101 response to the client // and return an instance of `WebSocketContext`. This class captures relevant information available at the time of the request and is a read-only // type - you cannot perform any actual IO operations such as sending or receiving using the `WebSocketContext`. These operations can be // performed by accessing the `System.Net.WebSocket` instance via the `WebSocketContext.WebSocket` property. private async void ProcessRequest(HttpListenerContext listenerContext) { WebSocketContext webSocketContext = null; try { // When calling `AcceptWebSocketAsync` the negotiated subprotocol must be specified. This sample assumes that no subprotocol // was requested. webSocketContext = await listenerContext.AcceptWebSocketAsync(subProtocol : null); Interlocked.Increment(ref count); Console.WriteLine("Processed: {0}", count); } catch (Exception e) { // The upgrade process failed somehow. For simplicity lets assume it was a failure on the part of the server and indicate this using 500. listenerContext.Response.StatusCode = 500; listenerContext.Response.Close(); Console.WriteLine("Exception: {0}", e); return; } webSocket = webSocketContext.WebSocket; try { //### Receiving // Define a receive buffer to hold data received on the WebSocket connection. The buffer will be reused as we only need to hold on to the data // long enough to send it back to the sender. //byte[] receiveBuffer = new byte[16000]; // While the WebSocket connection remains open run a simple loop that receives data and sends it back. while (webSocket.State == WebSocketState.Open) { // The first step is to begin a receive operation on the WebSocket. `ReceiveAsync` takes two parameters: // // * An `ArraySegment` to write the received data to. // * A cancellation token. In this example we are not using any timeouts so we use `CancellationToken.None`. // // `ReceiveAsync` returns a `Task<WebSocketReceiveResult>`. The `WebSocketReceiveResult` provides information on the receive operation that was just // completed, such as: // // * `WebSocketReceiveResult.MessageType` - What type of data was received and written to the provided buffer. Was it binary, utf8, or a close message? // * `WebSocketReceiveResult.Count` - How many bytes were read? // * `WebSocketReceiveResult.EndOfMessage` - Have we finished reading the data for this message or is there more coming? while (true) { Console.WriteLine("Receiving data"); WebSocketReceiveResult result; //WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None); int bufferSize = 1000; var buffer = new byte[bufferSize]; var offset = 0; var free = buffer.Length; while (true) { result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer, offset, free), CancellationToken.None); offset += result.Count; free -= result.Count; if (result.EndOfMessage) { break; } if (free == 0) { // No free space // Resize the outgoing buffer var newSize = buffer.Length + bufferSize; // Check if the new size exceeds a limit // It should suit the data it receives // This limit however has a max value of 2 billion bytes (2 GB) if (newSize > 2000000000) { throw new Exception("Maximum size exceeded"); } var newBuffer = new byte[newSize]; Array.Copy(buffer, 0, newBuffer, 0, offset); buffer = newBuffer; free = buffer.Length - offset; } } Console.WriteLine("Received data:"); Console.Write("Data byte size: " + buffer.Length); if (Encoding.ASCII.GetString(buffer).Contains("__ping__")) { //send pong, reset Console.WriteLine("Sending pong back"); string s = "__pong__"; //int bufferSize2 = 1000; var buffer2 = Encoding.ASCII.GetBytes(s); var offset2 = 0; var free2 = buffer2.Length; System.ArraySegment <byte> spong = new ArraySegment <byte>(buffer2, offset2, free2);//Encoding.UTF8.GetBytes(s); await webSocket.SendAsync(spong, WebSocketMessageType.Binary, result.EndOfMessage, CancellationToken.None); continue; } // The WebSocket protocol defines a close handshake that allows a party to send a close frame when they wish to gracefully shut down the connection. // The party on the other end can complete the close handshake by sending back a close frame. // // If we received a close frame then lets participate in the handshake by sending a close frame back. This is achieved by calling `CloseAsync`. // `CloseAsync` will also terminate the underlying TCP connection once the close handshake is complete. // // The WebSocket protocol defines different status codes that can be sent as part of a close frame and also allows a close message to be sent. // If we are just responding to the client's request to close we can just use `WebSocketCloseStatus.NormalClosure` and omit the close message. if (result.MessageType == WebSocketMessageType.Close) { await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); Console.WriteLine("Closing commmunication received from client websocketmessagetype.close"); break; } // This echo server can't handle text frames so if we receive any we close the connection with an appropriate status code and message. //else if (receiveResult.MessageType == WebSocketMessageType.Text) //{ // await webSocket.CloseAsync(WebSocketCloseStatus.InvalidMessageType, "Cannot accept text frame", CancellationToken.None); // Console.WriteLine("Closing commmunication received from client websocketmessagetype.text"); // break; //} // Otherwise we must have received binary data. Send it back by calling `SendAsync`. Note the use of the `EndOfMessage` flag on the receive result. This // means that if this echo server is sent one continuous stream of binary data (with EndOfMessage always false) it will just stream back the same thing. // If binary messages are received then the same binary messages are sent back. else { string s = Encoding.ASCII.GetString(buffer); //var sz = JsonConvert.SerializeObject(s); //Console.WriteLine("JSON data received:"); //Console.WriteLine(sz); //s = Encoding.ASCII.GetString(s); //Console.WriteLine("Sending data back and closing"); //await webSocket.SendAsync(new ArraySegment<byte>(receiveBuffer, 0, receiveResult.Count), WebSocketMessageType.Binary, receiveResult.EndOfMessage, CancellationToken.None); //rnk.ExecuteWork(); //break; } // The echo operation is complete. The loop will resume and `ReceiveAsync` is called again to wait for the next data frame. } } } catch (Exception e) { // Just log any exceptions to the console. Pretty much any exception that occurs when calling `SendAsync`/`ReceiveAsync`/`CloseAsync` is unrecoverable in that it will abort the connection and leave the `WebSocket` instance in an unusable state. Console.WriteLine("Exception: {0}", e); //DTT.AddWrite(e.ToString()); //DTT.Write(); } finally { //DTT.Write(); // Clean up by disposing the WebSocket once it is closed/aborted. if (webSocket != null) { webSocket.Dispose(); } } }
protected static bool DefaultHandledRequest(HttpListenerContext context) => false;
public ClientExecutor(HttpListenerContext context, string[] music) { this.context = context; this.music = music; }
/// <summary> /// Gets the request path for the specified context case sensitive. /// </summary> /// <param name="context">The context.</param> /// <returns>Path for the specified context</returns> public static string RequestPathCaseSensitive(this HttpListenerContext context) => context.Request.Url.LocalPath;
/// <summary> /// Gets the value for the specified query string key. /// If the value does not exist it returns null. /// </summary> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <returns>A string that represents the value for the specified query string key</returns> public static string QueryString(this HttpListenerContext context, string key) => context.InQueryString(key) ? context.Request.QueryString[key] : null;
private void GenerateResponse(HttpListenerContext context) { var request = context.Request; HttpListenerResponse response = context.Response; try { RouteTable m = null; if (request.HttpMethod == "GET") { m = Get; } else if (request.HttpMethod == "PUT") { m = Put; } else if (request.HttpMethod == "DELETE") { m = Delete; } if (m == null) { SetResponseNotFound(response); } else { var f = m.Match(request); if (f != null) { var r = f(request); if (r is string) { SetResponseContent(response, (string)r); } else if (r is Action <HttpListenerResponse> ) { var action = (Action <HttpListenerResponse>)r; action(response); } else if (r is Action <HttpListenerResponse, IPrincipal> ) { var action = (Action <HttpListenerResponse, IPrincipal>)r; action(response, context.User); } else if (r is int || r is HttpStatusCode) { response.StatusCode = (int)r; } foreach (var warning in ServerWarnings) { response.Headers.Add(ProtocolConstants.ServerWarningHeader, warning); } } else { SetResponseNotFound(response); } } } finally { response.OutputStream.Close(); } }
public ActionResult Redirect(HttpListenerContext context) { HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; string url = request.RawUrl.ToString(); string httpsvr = @"http://*****:*****@"Cache" + Path.DirectorySeparatorChar + "mukioplayerplus.swf"); if (File.Exists(cache)) { return(response.SendFile(new FileResponse() { FilePath = cache })); } else { return(ActionResult.NotHandled); } } //Flash player skin if (url.Contains("skin/") && url.EndsWith(".zip", StringComparison.CurrentCultureIgnoreCase)) { string zipfilename = Path.GetFileName(url); string cache = Path.Combine(Application.StartupPath, @"Cache\" + zipfilename); if (File.Exists(cache)) { return(response.SendFile(new FileResponse() { FilePath = cache })); } else { return(ActionResult.NotHandled); } } //Get Video by id if (url.Contains("getVideoByID.aspx?vid=")) { return(response.SendXmlFromResource(new ResourceStringResponse() { ResourceType = typeof(MukioRes), ResourceName = "Mukiogetvideobyid" })); } //ban list if (url.Contains("ban.json")) { return(response.SendXmlFromResource(new ResourceStringResponse() { ResourceType = typeof(MukioRes), ResourceName = "Mukioban" })); } if (url.Contains("newad.xml")) { return(response.SendXmlFromResource(new ResourceStringResponse() { ResourceType = typeof(MukioRes), ResourceName = "Mukionewad" })); } if (url.Contains("v_play.php?vid=") || url.Contains("t_play") || url.Contains("permanent")) { return(response.SendConfig(new ConfigResponse() { Videos = new List <Video>(AcPlayConfiguration.Config.Videos), StartupPath = AcPlayConfiguration.Config.StartupPath, ServerUrl = "http://*****:*****@"comment_on\.xml") || Regex.IsMatch(url, @"/\d+\.xml")) { return(response.SendComment(new CommentResponse() { PlayerName = "bilibili", CommentNumber = 0, SubtitleFiles = new List <string>(AcPlayConfiguration.Config.Subtitles), StartupPath = AcPlayConfiguration.Config.StartupPath })); } if (Regex.IsMatch(url, @"\d+_lock\.json")) //url.Contains("10000_lock.json")) { return(response.SendComment(new CommentResponse() { PlayerName = "Mukio", CommentNumber = 1, SubtitleFiles = new List <string>(AcPlayConfiguration.Config.Subtitles), StartupPath = AcPlayConfiguration.Config.StartupPath })); } if (url.Contains("u.json")) { return(response.SendXmlFromResource(new ResourceStringResponse() { ResourceType = typeof(MukioRes), ResourceName = "Mukiou" })); } if (url.Contains("updateVideoByContentID.aspx")) { return(response.SendXmlFromResource(new ResourceStringResponse() { ResourceType = typeof(MukioRes), ResourceName = "Mukioupdatevideobycontentid" })); } if (url.Contains("conf.xml")) { return(response.SendXmlFromResource(new ResourceStringResponse() { ResourceType = typeof(MukioRes), ResourceName = "mukioconf" })); } if (url.Contains("cnmd.aspx") || url.Contains("/post")) { var content = new StreamReader(request.InputStream, Encoding.ASCII).ReadToEnd(); Debug2.WriteLine("REQUEST DATA:" + Environment.NewLine + content); response.StatusCode = 200; response.Close(); return(ActionResult.Handled); } return(ActionResult.NotHandled); }
/// <summary> /// Gets the session object associated to the current context. /// Returns null if the LocalSessionWebModule has not been loaded. /// </summary> /// <param name="server">The server.</param> /// <param name="context">The context.</param> /// <returns>A session info for the given server context</returns> public static SessionInfo GetSession(this WebServer server, HttpListenerContext context) { return server.SessionModule?.GetSession(context); }
/// <summary> /// Deletes the session object associated to the current context. /// </summary> /// <param name="server">The server.</param> /// <param name="context">The context.</param> public static void DeleteSession(this WebServer server, HttpListenerContext context) { server.SessionModule?.DeleteSession(context); }
/// <summary> /// Deletes the session object associated to the current context. /// </summary> /// <param name="context">The context.</param> /// <param name="server">The server.</param> public static void DeleteSession(this HttpListenerContext context, WebServer server) { server.DeleteSession(context); }
/// <summary> /// Returns dictionary from Request POST data /// Please note the underlying input stream is not rewindable. /// </summary> /// <param name="context">The context to request body as string</param> /// <returns>A collection that represents KVPs from request data</returns> public static Dictionary<string, object> RequestFormDataDictionary(this HttpListenerContext context) => RequestFormDataDictionary(context.RequestBody());
/// <summary> /// Outputs a Json Response given a data object /// </summary> /// <param name="context">The context.</param> /// <param name="data">The data.</param> /// <returns>A true value of type ref=JsonResponseAsync"</returns> public static bool JsonResponse(this HttpListenerContext context, object data) { return context.JsonResponseAsync(data).GetAwaiter().GetResult(); }
/// <summary> /// Parses the json as a given type from the request body. /// Please note the underlying input stream is not rewindable. /// </summary> /// <typeparam name="T">The type of specified object type</typeparam> /// <param name="context">The context.</param> /// <returns> /// Parses the json as a given type from the request body /// </returns> public static T ParseJson<T>(this HttpListenerContext context) where T : class { return ParseJson<T>(context.RequestBody()); }
/// <summary> /// Determines if a key exists within the Request's query string /// </summary> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <returns>True if a key exists within the Request's query string; otherwise, false</returns> public static bool InQueryString(this HttpListenerContext context, string key) => context.Request.QueryString.AllKeys.Contains(key);
private static void Main(string[] args) { 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(); foreach (string s in args) { Console.WriteLine("Listening for connections on " + s); } while (true) { // Note: The GetContext method blocks while waiting for a request. HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; Header header = new Header(request); string documentContents; using (Stream receiveStream = request.InputStream) { using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8)) { documentContents = readStream.ReadToEnd(); } } header.printAllHeader(); header.printHeader(HttpRequestHeader.ContentType); //MIME header.printHeader(HttpRequestHeader.Cookie); //Cookie header.printHeader(HttpRequestHeader.UserAgent); // L’agent utilisateur demandeur header.printHeader(HttpRequestHeader.AcceptEncoding); // les encodages de contenu admis pour la réponse header.printHeader(HttpRequestHeader.Authorization); // les informations d’identification que le client doit présenter pour s’authentifier auprès du serveur header.printHeader(HttpRequestHeader.ContentLanguage); // langages naturels préférés pour la réponse header.printHeader(HttpRequestHeader.AcceptCharset); //les jeux de caractères admis pour la réponse header.printHeader(HttpRequestHeader.Allow); // le jeu de méthodes HTTP pris en charge Console.WriteLine($"Received request for {request.Url}"); 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 ... // listener.Stop(); }
/// <summary> /// Retrieves the Request HTTP Verb (also called Method) of this context. /// </summary> /// <param name="context">The context.</param> /// <returns>HTTP verb result of the conversion of this context</returns> public static HttpVerbs RequestVerb(this HttpListenerContext context) { Enum.TryParse(context.Request.HttpMethod.ToLowerInvariant().Trim(), true, out HttpVerbs verb); return verb; }
protected override void ProcessRequest(HttpListenerContext context) { Logger.Info("Received: " + context.Request.HttpMethod + " " + context.Request.RawUrl); base.ProcessRequest(context); }
/// <summary> /// Gets the request path for the specified context. /// </summary> /// <param name="context">The context.</param> /// <returns>Path for the specified context</returns> public static string RequestPath(this HttpListenerContext context) => context.Request.Url.LocalPath.ToLowerInvariant();
private void RequestReceived(HttpAsyncServer sender, HttpListenerContext context) { var entity = new HttpEntity(context.Request, context.Response, context.User, _logHttpRequests, _advertiseAsAddress, _advertiseAsPort); _requestsMultiHandler.Handle(new IncomingHttpRequestMessage(this, entity, _requestsMultiHandler)); }
public HttpListenerResponse(HttpListenerContext context) { Response = context.Response; }
/// <summary> /// Requests the regex URL parameters. /// </summary> /// <param name="context">The context.</param> /// <param name="basePath">The base path.</param> /// <returns>The params from the request.</returns> public static Dictionary<string, object> RequestRegexUrlParams(this HttpListenerContext context, string basePath) => RequestRegexUrlParams(context.RequestPath(), basePath);
protected abstract IEnumerable <T> CreateNewItemsFromContext(HttpListenerContext context);
/// <summary> /// Requests the wildcard URL parameters. /// </summary> /// <param name="context">The context.</param> /// <param name="basePath">The base path.</param> /// <returns>The params from the request.</returns> public static string[] RequestWildcardUrlParams(this HttpListenerContext context, string basePath) => RequestWildcardUrlParams(context.RequestPath(), basePath);
static void JsonPack() { //while (true) do { HttpListenerContext context = _httpListener.GetContext(); HttpListenerRequest request = context.Request; serverStillResponding = true; NameValueCollection queryStringCollection = request.QueryString; js.Info = new List <string>(); js.Info.Add("INFO: here are parameters what can be used .."); js.Info.Add("How? Add them into IP address in above e.g. ?timeout=100&antennapower=2300"); js.Info.Add("PARAMETERS:"); js.Info.Add("timeout - with this you can change timeout value (ms) for RFID read loop e.g. 500"); js.Info.Add("antennapower - with 4 number value you can change Antenna Read Power value (max: 27 dBm) e.g. 2700"); if (request.HttpMethod != null) { js.requestType = request.HttpMethod; } //js.UsedParameters = request.QueryString; js.UsedParameters = new List <SimpleObject>(); foreach (String key in queryStringCollection.AllKeys) { Console.WriteLine("Key: " + key + " Value: " + queryStringCollection[key]); SimpleObject t = new SimpleObject(); t.Key = key; t.Value = queryStringCollection[key]; if (t.Key == "timeout") { int tmpValue = System.Convert.ToInt32(t.Value); Console.WriteLine("New timeout value given: " + tmpValue); //TODO: ADD HERE A PUBLIC PARAMETER WHERE YOU CAN SET THIS GIVEN VALUE !? thresholdValueForThreadSleep = tmpValue; } if (t.Key == "antennapower") { int tmpValue = System.Convert.ToInt32(t.Value); if (tmpValue > 2700) { Console.WriteLine("***PROBLEM: given antenna power value: " + tmpValue + " was too high (max: 2700 i.e. 27 dBm), so default value to be used."); string tmpStr = "2700"; t.Value = tmpStr; rfidAntennapower = tmpValue; } } //tämä arvo ei muuta mitään rfid threadissa rfth.Abort(); Console.WriteLine("New antenna power value given: " + t.Value); rfth = new Thread(new ThreadStart(RFIDInit)); rfth.Start(); js.UsedParameters.Add(t); // NOTICE that given parameter handling is before that code line. } string json = JsonConvert.SerializeObject(js); if (request.HttpMethod == "GET") { // Here i can read all parameters in string but how to parse each one i don't know Console.WriteLine("-NOTE- Server ok"); } byte[] _responseArray = Encoding.UTF8.GetBytes(json); context.Response.OutputStream.Write(_responseArray, 0, _responseArray.Length); // write bytes to the output stream //context.Response.KeepAlive = false; // set the KeepAlive bool to false context.Response.Close(); // close the connection Console.WriteLine("Respone given to a request."); //json osuus loppuu if (cacheIsUptodate) { js.rfidDataToString.Clear(); } Thread.Sleep(300); //little delay to prevent spamming serverStillResponding = false; }while (!serverStillResponding); }
/// <summary> /// Determines whether [has request header] [the specified context]. /// </summary> /// <param name="context">The context.</param> /// <param name="headerName">Name of the header.</param> /// <returns>True if request headers is not a null; otherwise, false</returns> public static bool HasRequestHeader(this HttpListenerContext context, string headerName) => context.Request.Headers[headerName] != null;
public static string log_path; //日志路径 static void Main(string[] args) { #region 启动信息 int platform_id = 0; if (args.Length > 0) { platform_id = Convert.ToInt32(args[0]); } Console.WriteLine("*****************************************"); Console.Write("服务器名:\tRechargeServer"); #if _TEST Console.Write("(测试版)"); #endif Console.Write("\n运行版本:\t"); #if DEBUG Console.WriteLine("Debug"); #else Console.WriteLine("Release"); #endif Console.Write("启动时间:\t"); Console.WriteLine(DateTime.Now); Console.WriteLine("平台ID:\t\t" + platform_id); Console.WriteLine("*****************************************"); #endregion //系统是否支持 if (!HttpListener.IsSupported) { Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class."); return; } log_path = @".\recharge_log\"; if (!Directory.Exists(log_path)) { Directory.CreateDirectory(log_path); } log_path += DateTime.Now.ToString("yyyyMdHHmm") + ".log"; #if _TEST NewConnection(platform_id); #else NewConnection(platform_id); #endif try { mysql_connect.Open(); } catch (Exception ex) { Console.WriteLine(ex); Console.WriteLine("连接数据库失败"); return; } new Thread(QueryLoop).Start(); //打开监听 HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://+:8080/game/pay/"); listener.Prefixes.Add("http://+:8080/game/userExists/"); listener.Start(); Console.WriteLine("Start Listening..."); try { while (true) { HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; if (request.HttpMethod == "GET") { int result = 0; if (request.RawUrl.Contains("game/userExists?")) { result = CheckUser(request); } else if (request.RawUrl.Contains("game/pay?")) { result = Recharge(request); } HttpListenerResponse response = context.Response; string responseString = result.ToString(); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; System.IO.Stream output = response.OutputStream; output.Write(buffer, 0, buffer.Length); output.Close(); } } } catch (Exception ex) { Console.WriteLine(ex); } finally { listener.Stop(); mysql_connect.Close(); } Console.ReadLine(); }
/// <summary> /// Retrieves the specified request the header. /// </summary> /// <param name="context">The context.</param> /// <param name="headerName">Name of the header.</param> /// <returns>Specified request the header when is true; otherwise, empty string </returns> public static string RequestHeader(this HttpListenerContext context, string headerName) => context.Request.Headers[headerName] ?? string.Empty;
/// <summary> /// Gets the session object associated to the current context. /// Returns null if the LocalSessionWebModule has not been loaded. /// </summary> /// <param name="context">The context.</param> /// <param name="server">The server.</param> /// <returns>A session object for the given server context</returns> public static SessionInfo GetSession(this HttpListenerContext context, WebServer server) { return server.GetSession(context); }
/// <summary> /// Outputs a Json Response given a Json string /// </summary> /// <param name="context">The context.</param> /// <param name="json">The json.</param> /// <returns> /// A true value of type ref=JsonResponseAsync"</returns> public static bool JsonResponse(this HttpListenerContext context, string json) { return context.JsonResponseAsync(json).GetAwaiter().GetResult(); }