JSONRpc Client over websocket C#



我需要一个JSON-Rpc客户端通过websocket与服务器进行通信。特别是,我需要创建一个接口并使用方法将 JSON 请求发送到服务器。

有人知道如何做到这一点吗?

我找到了StreamJsonRpc库,但它适用于流而不是 websocket。

我可以从 websocket 连接获取流并将其 pas 到StreamJsonRpc吗?
你还有其他想法吗?

你只需要 Json.net 和WebSocket4Net。

你可以看到那里。

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Security.Authentication;
using WebSocket4Net;
namespace LightStreamSample
{
class WebSocket4NetSample
{
static void Main(string[] args)
{
var channelName = "[your websocket server channel name]";
// note: reconnection handling needed.
var websocket = new WebSocket("wss://[your web socket server websocket url]", sslProtocols: SslProtocols.Tls12);
websocket.Opened += (sender, e) =>
{
websocket.Send(
JsonConvert.SerializeObject(
new
{
method = "subscribe",
@params = new { channel = channelName },
id = 123,
}
)
);
};
websocket.MessageReceived += (sender, e) =>
{
dynamic data = JObject.Parse(e.Message);
if (data.id == 123)
{
Console.WriteLine("subscribed!");
}
if (data.@params != null)
{
Console.WriteLine(data.@params.channel + " " + data.@params.message);
}
};
websocket.Open();
Console.ReadKey();
}
}
}

为了更新这篇文章,现在可以使用 StreamJsonRpc 从 websocket 传递流。

Github websocket 示例。网芯

using (var jsonRpc = new JsonRpc(new WebSocketMessageHandler(socket)))
{
try
{
jsonRpc.AddLocalRpcMethod("Tick", new Action<int>(tick => Console.WriteLine($"Tick {tick}!")));
jsonRpc.StartListening();
Console.WriteLine("JSON-RPC protocol over web socket established.");
int result = await jsonRpc.InvokeWithCancellationAsync<int>("Add", new object[] { 1, 2 }, cancellationToken);
Console.WriteLine($"JSON-RPC server says 1 + 2 = {result}");
// Request notifications from the server.
await jsonRpc.NotifyAsync("SendTicksAsync");
await jsonRpc.Completion.WithCancellation(cancellationToken);
}
catch (OperationCanceledException)
{
// Closing is initiated by Ctrl+C on the client.
// Close the web socket gracefully -- before JsonRpc is disposed to avoid the socket going into an aborted state.
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Client closing", CancellationToken.None);
throw;
}
}

.Net Framework实现类似,但略有不同

最新更新