public static async void SendResponse(ResponseEntity data, HttpListenerContext currentContext) { await Task.Run(async() => { try { data.ParseHeadersIntoContext(currentContext); var byteBuffer = data.GetDataAsBytes(); currentContext.Response.ContentLength64 = byteBuffer.Length; await currentContext.Response.OutputStream.WriteAsync(byteBuffer, 0, byteBuffer.Length); currentContext.Response.OutputStream.Close(); var eventData = new ServerEventData { status = currentContext.Response.StatusCode, exception = null, message = currentContext.Request.HttpMethod, path = currentContext.Request.Url.AbsolutePath }; onRequestFinishedProcessing?.Invoke(eventData); } catch (Exception e) { try { throw new InternalServerErrorException(e.Message, currentContext, e); } catch (InternalServerErrorException ex) { ExceptionHandler.HandleException(ex, currentContext); } } }); }
static Server() { serverThread = new Thread(KeepThreadAlive); ContextRunner.onRequestFinishedProcessing += (msg) => onRequestReceived?.Invoke(msg); ExceptionHandler.onError += (err) => { var serverEvent = new ServerEventData(null, null, err, null); onServerError?.Invoke(serverEvent); }; ServiceAttribute.RegisterServices(); }
public static void LogMessage(ServerEventData eventData) { string message = ""; if (eventData.exception != null) { Console.WriteLine(eventData.exception.ToString()); } if (eventData.path != null) { message += $"{eventData.path.ToString()}"; } if (eventData.status != null) { message += $" {eventData.status.ToString()}"; } if (eventData.message != null) { message += $" -- {eventData.message}"; } Console.WriteLine(message); }
/// <summary> /// Automatically find all (GET|POST|DELETE|PUT|PATCH)Mapping controllers and register them as endpoints /// </summary> public static void RegisterEndpoints() { int controllerCount = 0; foreach (var controller in Assembly.GetCallingAssembly().GetTypes()) { if (controller.GetCustomAttribute <RestController>() != null) { RestController.ExtractRequestMethods(controller); controllerCount++; } } if (controllerCount > 0) { var eventData = new ServerEventData { exception = null, message = $"Found {controllerCount} {(controllerCount > 1 ? "controllers" : "controller")}", path = null, status = null }; onEndpointRegistrationFinished?.Invoke(eventData); } }
private void ServerStopEvent(ServerEventData data) { serverStop.Set(); }
private void ServerStartEvent(ServerEventData data) { serverStart.Set(); }
internal virtual void ServerOnClientReceive(ServerEventData data) { }
internal virtual void ServerOnClientTimeout(ServerEventData data) { }
internal virtual void ServerOnClientDisconnect(ServerEventData data) { }
internal virtual void ServerOnClientConnect(ServerEventData data) { Debug.Log($"Client {data.PeerId} connected with address {data.PeerIp}"); Server.AddToFilter(data.PeerId); }