Location>code7788 >text

Enable JSON-RPC in Core using StreamJsonRpc

Popularity:53 ℃/2025-04-12 19:07:33

StreamJsonRpc is an open source library developed by Microsoft to implement remote procedure calls (RPC) based on the JSON-RPC 2.0 specification in the .NET platform. It realizes efficient cross-process or cross-network communication through streams (such as pipelines, network flows, etc.), and is especially suitable for scenarios where lightweight and flexible communication is required. The following is a detailed introduction to StreamJsonRpc, combined with the key points in the reference article you provide:


1. Core features

  1. Stream-based communicationSupportedStreamPipeorIDuplexPipeIt performs data transmission, suitable for various underlying transmission mechanisms such as pipelines, network sockets, WebSockets, etc.
  1. Two-way communicationAllow the client and the server to call methods from each other to realize two-way interaction (such as the client initiates a request and the server actively pushes notifications).
  1. Strong type supportDefining contracts through interfaces, method calls and parameter passing support strong typing, reducing manual serialization/deserialization work.
  1. Asynchronous ModelAll methods support asynchronous by default (async/await), suitable for high concurrency and low latency scenarios.
  1. Cross-platform compatibilityCompatible with .NET Standard 2.0, it can be used in environments such as .NET Core, .NET Framework, and Xamarin.
  1. ExtensibilityProvide custom message formatting (e.g.MessagePackor customize JSON serializer), error handling, logging and other extension points.

2. Integration in Core

The reference article shows how to integrate StreamJsonRpc into a Core application to enable HTTP or WebSocket-based RPC communication. Here are the key steps:

2.1 Configure the server

  1. Add NuGet package

    Install-Package StreamJsonRpc

    Plain Text

  1. Define RPC interface

    public interface IGreeterRpcService

    {

    Task<string> GreetAsync(string name);

    }

    Plain Text

  1. Implement services

    public class GreeterRpcService : IGreeterRpcService

    {

    public Task<string> GreetAsync(string name) => ($"Hello, {name}!");

    }

    Plain Text

  1. Configure Core MiddlewareuseUseWebSockets()Enable WebSocket support and handle RPC requests:

    ();

    (async (context, next) =>

    {

    if ()

    {

    using var webSocket = await ();

    var service = new GreeterRpcService();

    await (webSocket, service);

    }

    else await next();

    });

    Plain Text

2.2 Client implementation

The client connects to the server through WebSocket or other streams and calls the remote method:

var webSocket = new ClientWebSocket();

await (new Uri("ws://localhost:5000"), );

var greeter = <IGreeterRpcService>(webSocket);

string result = await ("World");

(result); // Output "Hello, World!"



3. Advanced usage

  1. Two-way method callBoth the client and the server can define interfaces to realize two-way communication. For example, the server can proactively notify the client:

    // Define the interface that the client can call

    public interface IClientCallback

    {

    Task NotifyAsync(string message);

    }

    // Call the client in the server method

    public async Task SendNotificationAsync()

    {

    var callback = <IClientCallback>();

    await ("New event!");

    }

    Plain Text

  1. Custom serializationUsed by default, but can be replaced with other serializers (such as ):

    var options = new JsonRpcOptions

    {

    MessageFormatter = new SystemTextJsonFormatter()

    };

    (stream, service, options);

    Plain Text

  1. Error handlingpassJsonRpcExceptionCapture remote call exceptions, support custom error codes and data:

    try

    {

    await ("error");

    }

    catch (JsonRpcException ex)

    {

    ($"Error Code: {}, Message: {}");

    }

    Plain Text

  1. Performance optimization
  • useMemoryPoolorBufferManagerReduce memory allocation.
  • EnableMessagePackBinary protocol to reduce transmission overhead:

    Install-Package

    var formatter = new MessagePackFormatter();

    Plain Text


4. Applicable scenarios

  • Inter-microservice communication: Lightweight alternative to gRPC or REST.
  • Desktop application plug-in system: The main process communicates with the plug-in process.
  • Real-time application: Such as chat, real-time data push (combined with WebSocket).
  • Cross-language integration: Interact with other languages ​​(such as Python, JavaScript) through standard JSON-RPC.

5. Things to note

  • Thread safety: Ensure that the service implementation is thread-safe.
  • Timeout control: Configure for long-running methodsCancellationToken
  • Safety: Enable TLS to encrypt network flows and verify the caller's identity.

6. Reference resources

  • Official document: /microsoft/vs-streamjsonrpc
  • JSON-RPC 2.0 specification:
  • Sample project:/tpeczek/

With StreamJsonRpc, developers can quickly build efficient and flexible RPC systems, especially suitable for scenarios where custom communication protocols are required or integration with existing infrastructure.