Search code examples
c#websocketjson-rpc

JSONRpc Client over websocket C#


I need a JSON-Rpc client to communicate over websocket to the server. In particular, I need to create an interface and use methods to send JSON requests to the server.

Does someone know how to do that?

I found the StreamJsonRpc library, but it works over stream and not over websocket.

Can I get the stream from websocket connection and pas it to StreamJsonRpc?
Do you have other ideas?


Solution

  • You only need Json.net and WebSocket4Net.

    You can see there.

    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([email protected] + " " + [email protected]);
                    }
                };
    
                websocket.Open();
    
                Console.ReadKey();
            }
        }
    }