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
-
Stream-based communicationSupported
Stream
、Pipe
orIDuplexPipe
It performs data transmission, suitable for various underlying transmission mechanisms such as pipelines, network sockets, WebSockets, etc.
- 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).
- Strong type supportDefining contracts through interfaces, method calls and parameter passing support strong typing, reducing manual serialization/deserialization work.
-
Asynchronous ModelAll methods support asynchronous by default (
async/await
), suitable for high concurrency and low latency scenarios.
- Cross-platform compatibilityCompatible with .NET Standard 2.0, it can be used in environments such as .NET Core, .NET Framework, and Xamarin.
-
ExtensibilityProvide custom message formatting (e.g.
MessagePack
or 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
-
Add NuGet package
Install-Package StreamJsonRpc
Plain Text
-
Define RPC interface
public interface IGreeterRpcService
{
Task<string> GreetAsync(string name);
}
Plain Text
-
Implement services
public class GreeterRpcService : IGreeterRpcService
{
public Task<string> GreetAsync(string name) => ($"Hello, {name}!");
}
Plain Text
-
Configure Core Middlewareuse
UseWebSockets()
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
-
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
-
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
-
Error handlingpass
JsonRpcException
Capture remote call exceptions, support custom error codes and data:try
{
await ("error");
}
catch (JsonRpcException ex)
{
($"Error Code: {}, Message: {}");
}
Plain Text
- Performance optimization
- use
MemoryPool
orBufferManager
Reduce memory allocation.
-
Enable
MessagePack
Binary 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 methods
CancellationToken
。
- 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.