/// <summary> /// Process a string request which contains the json data. /// </summary> /// <param name="serviceName">The name of the service.</param> /// <param name="requestString">The request string</param> /// <param name="cancellationToken">The cancellation token which can cancel this method.</param> /// <returns>The response string.</returns> public async Task <string> ProcessAsync(string serviceName, string requestString, CancellationToken cancellationToken) { if (_router == null) { throw new NullReferenceException("The router is null"); } if (Logger.DebugMode) { Logger.WriteDebug($"Receive request data:{requestString}"); } using var utf8StringData = Utf8StringData.Get(requestString); var requestStream = utf8StringData.Stream; var requests = await JsonRpcCodec.DecodeRequestsAsync(requestStream, cancellationToken).ConfigureAwait(false); var responses = await _router.DispatchRequestsAsync(serviceName, requests, cancellationToken).ConfigureAwait(false); var responseData = await JsonRpcCodec.EncodeResponsesAsync(responses, cancellationToken).ConfigureAwait(false); var responseString = Encoding.UTF8.GetString(responseData); if (Logger.DebugMode) { Logger.WriteDebug($"Response data sent:{responseString}"); } return(responseString); }
/// <summary> /// Invoke remote method and get the result. /// </summary> /// <typeparam name="T">The return type.</typeparam> /// <param name="serviceName">The name of the service</param> /// <param name="methodName">The method name to call.</param> /// <param name="args">The parameters of the method.</param> /// <param name="cancellationToken">The cancellation token which can cancel this method.</param> /// <returns>The result value.</returns> public async Task <T> InvokeAsync <T>(string serviceName, string methodName, object[] args, CancellationToken cancellationToken = default) { var id = Interlocked.Increment(ref _requestId); var request = new JsonRpcRequest(id, methodName, new JsonRpcRequestParameter(RequestParameterType.Object, args)); var requestData = await JsonRpcCodec.EncodeRequestsAsync(new[] { request }, cancellationToken).ConfigureAwait(false); var responseData = await ProcessAsync(serviceName, requestData, cancellationToken).ConfigureAwait(false); var responses = await JsonRpcCodec.DecodeResponsesAsync(responseData, cancellationToken).ConfigureAwait(false); if (responses.Length > 0) { var response = responses[0]; var responseId = Convert.ToInt32(response.Id); if (responseId != id) { throw new InvalidOperationException("Response id is not matched."); } if (response.Result is RpcException exception) { throw exception; } var resultString = (string)response.Result; using var utf8StringData = Utf8StringData.Get(resultString); return(await JsonSerializer.DeserializeAsync <T>(utf8StringData.Stream, JsonRpcConvertSettings.SerializerOptions, cancellationToken).ConfigureAwait(false)); } throw new InvalidOperationException("Fail to get invoke result from server."); }