public void Start() { Interlocked.Exchange(ref _running, 1); _listener.Start(); Task.Run(async() => { try { var service = new WasabiJsonRpcService(); var handler = new JsonRpcRequestHandler(service); while (IsRunning) { var context = _listener.GetContext(); var request = context.Request; var response = context.Response; if (request.HttpMethod == "POST") { string body; using (var reader = new StreamReader(request.InputStream)) body = await reader.ReadToEndAsync(); var identity = (HttpListenerBasicIdentity)context.User?.Identity; if (!_config.RequiresCredentials || CheckValidCredentials(identity)) { var result = await handler.HandleAsync(body, _cts); // result is null only when the request is a notification. if (!string.IsNullOrEmpty(result)) { response.ContentType = "application/json-rpc"; var output = response.OutputStream; var buffer = Encoding.UTF8.GetBytes(result); await output.WriteAsync(buffer, 0, buffer.Length); await output.FlushAsync(); } } else { response.StatusCode = (int)HttpStatusCode.Unauthorized; } } else { response.StatusCode = (int)HttpStatusCode.MethodNotAllowed; } response.Close(); } } finally { Interlocked.CompareExchange(ref _running, 3, 2); // If IsStopping, make it stopped. } }); }
public JsonRpcServer(Global global, JsonRpcServerConfiguration config, TerminateService terminateService) { Config = config; Listener = new HttpListener(); Listener.AuthenticationSchemes = AuthenticationSchemes.Basic | AuthenticationSchemes.Anonymous; foreach (var prefix in Config.Prefixes) { Listener.Prefixes.Add(prefix); } Service = new WasabiJsonRpcService(global, terminateService); }