private void Worker() { WaitHandle[] wait = { _ready, _stop }; while (0 == WaitHandle.WaitAny(wait)) { HttpListenerContext context; lock (_queue) { if (_queue.Count > 0) { context = _queue.Dequeue(); } else { _ready.Reset(); continue; } } try { //ProcessRequest(context); this.HandleContext(context); } catch (ArgumentException) { Extras.WriteColoredLine("Incorrect request", ConsoleColor.Magenta); _statsApi.HandleIncorrect(context); } catch (ThreadAbortException) { return; } catch (Exception error) { _statsApi.HandleIncorrect(context); Extras.WriteColoredLine( $"Source: {error.Source}\nException: {error.Message}\nStack Trace: {error.StackTrace}", ConsoleColor.Red); } } }
//public event Action<HttpListenerContext> ProcessRequest; private void HandleContext(HttpListenerContext listenerContext) { // TODO: Make routing with regexp var request = listenerContext.Request; var parts = request.RawUrl.Split('/'); Extras.WriteColoredLine(String.Format("{1} {0}", request.RawUrl, request.HttpMethod), ConsoleColor.DarkGreen); if (parts[1] == "servers") { if (parts[2] == "info") { // /servers/info GET if (request.HttpMethod == HttpMethod.Get.Method) { _statsApi.GetServersInfo(listenerContext); } // If method is not get else { _statsApi.HandleIncorrect(listenerContext); } } else { switch (parts[3]) { case "info": // /servers/<endpoint>/info PUT, GET if (request.HttpMethod == HttpMethod.Get.Method) { _statsApi.GetServerInfo(listenerContext); } else if (request.HttpMethod == HttpMethod.Put.Method) { _statsApi.PutServerInfo(listenerContext); } else { _statsApi.HandleIncorrect(listenerContext); } break; case "matches": // /servers/<endpoint>/matches/<timestamp> PUT, GET if (request.HttpMethod == HttpMethod.Get.Method) { _statsApi.GetServerMatch(listenerContext); } else if (request.HttpMethod == HttpMethod.Put.Method) { _statsApi.PutServerMatch(listenerContext); } else { _statsApi.HandleIncorrect(listenerContext); } break; case "stats": // /servers/<endpoint>/stats GET _statsApi.GetServerStats(listenerContext); break; default: _statsApi.HandleIncorrect(listenerContext); break; } } } else if (parts[1] == "reports" && request.HttpMethod == HttpMethod.Get.Method) { switch (parts[2]) { case "recent-matches": _statsApi.GetRecentMatchesReport(listenerContext); break; case "best-players": _statsApi.GetBestPlayersReport(listenerContext); break; case "popular-servers": _statsApi.GetPopularServersReport(listenerContext); break; default: _statsApi.HandleIncorrect(listenerContext); break; } } else if (parts[1] == "players" && parts[3] == "stats" && request.HttpMethod == HttpMethod.Get.Method) { _statsApi.GetPlayerStats(listenerContext); } else { _statsApi.HandleIncorrect(listenerContext); } }