public Response(StreamSocket socket) { this.socket = socket; }
private async void ProcessRequestAsync(StreamSocket socket) { try { StringBuilder request = new StringBuilder(); byte[] data = new byte[BufferSize]; IBuffer buffer = data.AsBuffer(); uint dataRead = BufferSize; using (IInputStream input = socket.InputStream) { while (dataRead == BufferSize) { await Task.Delay(50); var result = await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial); request.Append(Encoding.UTF8.GetString(data, 0, (int)result.Length)); dataRead = result.Length; } } // Costruiamo le nostre request e response var req = new Request(request.ToString()); var res = new Response(socket); if (req.Method == null) { await res.SendStatusAsync(400); // Bad request return; } var path = req.Path; bool handled = false; // Gestione delle routes switch (req.Method) { case "GET": // Togliamo la querystring che eventualmente possiamo gestire a parte path = path.LastIndexOf('?') > 0 ? path.Substring(0, path.LastIndexOf('?')) : path; var parts = path.Split('/'); foreach (var t in getRoutes) { var fileName = parts[parts.Length - 1]; if (t.Item1.LastIndexOf('.') > 0 && fileName.LastIndexOf('.') > 0) { var extension1 = fileName.Substring(fileName.LastIndexOf('.')); var extensionExpected = t.Item1.Substring(t.Item1.LastIndexOf('.')); if (extension1 == extensionExpected) { await t.Item2(req, res); handled = true; break; } } if (t.Item1 == path) { await t.Item2(req, res); handled = true; break; } } if (!handled) { await res.SendStatusAsync(404); } break; case "POST": foreach (var t in postRoutes) { if (t.Item1 == path) { await t.Item2(req, res); handled = true; break; } } if (!handled) { await res.SendStatusAsync(404); } break; default: Debug.WriteLine("HTTP method not supported: " + req.Method); await res.SendStatusAsync(501); //Not implemented break; } } catch (Exception ex) { Debug.WriteLine(ex.Message); } finally { await socket.CancelIOAsync(); socket.Dispose(); } }