在C#中使用Websocket实现JSON-RPC客户端

4
我需要一个JSON-Rpc客户端通过websocket与服务器通信。特别地,我需要创建一个接口并使用方法向服务器发送JSON请求。
有人知道如何做到吗?
我找到了StreamJsonRpc库,但它只适用于流而不是websocket。
我能从websocket连接获取流并将其传递给StreamJsonRpc吗?
还有其他想法吗?
2个回答

3

你只需要用到 Json.netWebSocket4Net

你可以在 这里 看到。

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();
        }
    }
}

谢谢,我会遵循您的建议来开发我的应用程序。 - Mattia

1

更新此帖,现在可以使用StreamJsonRpc传递来自websocket的流。

.NetCore的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框架的实现方式类似但略有不同。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接