private async Task <FlexResponse> ProcessRequest(FlexRequest request) { Func <FlexRequest, Task <FlexResponse> > processor = null; if (request.Method == "GET") { Get.TryGetValue(request.Url, out processor); } else if (request.Method == "POST") { Post.TryGetValue(request.Url, out processor); } else if (request.Method == "PUT") { Put.TryGetValue(request.Url, out processor); } else if (request.Method == "DELETE") { Delete.TryGetValue(request.Url, out processor); } if (processor != null) { FlexResponse response = await processor(request); return(response); } return(DefaultResponse); }
public static FlexRequest TryParse(string requestRaw) { try { FlexRequest httpRequest = new FlexRequest(); string[] linesRaw = requestRaw.Split(new[] { "\r\n" }, StringSplitOptions.None); string[] request = linesRaw[0].Split(' '); httpRequest.Method = request[0].ToUpperInvariant(); string completeQuery = request[1]; string[] queryString = completeQuery.Split('?'); httpRequest.Url = queryString[0]; if (queryString.Length > 1) { httpRequest.QueryParameters = ParseQueryString(queryString[1]); } httpRequest.Protocol = request[2]; for (int i = 1; i < linesRaw.Length; ++i) { string line = linesRaw[i]; // content begins if (String.IsNullOrEmpty(line)) { StringBuilder contentBuilder = new StringBuilder(); for (int j = i + 1; j < linesRaw.Length; ++j) { contentBuilder.AppendLine(linesRaw[j]); } httpRequest.Body = contentBuilder.ToString(); break; } // header int separater = line.IndexOf(":"); string key = line.Substring(0, separater); string value = line.Substring(separater + 2); httpRequest.Header[key] = value; } return(httpRequest); } catch { // error while parsing return(null); } }
private async void ListenerConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { StreamSocket socket = args.Socket; StringBuilder requestStrBuilder = new StringBuilder(); using (IInputStream input = socket.InputStream) { byte[] data = new byte[BufferSize]; IBuffer buffer = data.AsBuffer(); uint dataRead = BufferSize; while (dataRead == BufferSize) { await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial); requestStrBuilder.Append(Encoding.UTF8.GetString(data, 0, (int)buffer.Length)); dataRead = buffer.Length; } } string requestStr = requestStrBuilder.ToString(); if (String.IsNullOrEmpty(requestStr)) { return; } FlexRequest request = FlexRequest.TryParse(requestStr); if (request == null) { return; } FlexResponse response = await ProcessRequest(request); using (IOutputStream output = socket.OutputStream) { using (Stream responseStream = output.AsStreamForWrite()) { await response.WriteToStream(responseStream); await responseStream.FlushAsync(); } } }