Multispeed
Multispeed

Reputation: 97

Websocket client connection in c# windows forms

I'm looking for the way to get data from server using websocket convert them to .json and store them sqlite db to use filtered data in winforms. i tried some examples from internet but couldn't get them working.

Tried this python code:

import websocket
import ssl

SOCKET = "wss://xxxxx.io:33010/ws/?EIO=3&transport=websocket"


def on_open(ws):
    print('connection: successful')

def on_close(ws, *args):
    print('connection: lost')

def on_message(ws, message):
    print(message)

def on_error(ws, message):
    print(message)

ws = websocket.WebSocketApp(SOCKET, on_open=on_open, on_close=on_close, on_message=on_message, on_error=on_error)
ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})

and from this Open Source web link http://livepersoninc.github.io/ws-test-page/?

From both i was getting data from server, but i need something similar only in C# any ideas.

Example text/json from server:

42["ticker",[{"provider":"lbank","pair":"zec_usdt","from":"ZEC","rate":126.435645,"to":"USDT","timeUtc":1651350906458,"key":"lbank:zec_usdt:1651350906458"}]]
42["ticker",[{"provider":"lbank","pair":"bch_usdt","from":"BCH","rate":285.82794,"to":"USDT","timeUtc":1651350906470,"key":"lbank:bch_usdt:1651350906470"}]]

Upvotes: 1

Views: 8115

Answers (2)

Milind Morey
Milind Morey

Reputation: 2116

PM> Install-Package WebSocketSharp -Pre
 
using WebSocketSharp 


        private WebSocket client;
        const string host = “ws://127.0.0.1:8000”;

        private void Form1_Load(object sender, EventArgs e)
        {
            client = new WebSocket(host);

            client.OnOpen += (ss, ee) =>
               listBox1.Items.Add(string.Format(“Connected to {0} successfully “, host));
            client.OnError += (ss, ee) =>
               listBox1.Items.Add(”     Error: “ + ee.Message);
            client.OnMessage += (ss, ee) =>
               listBox1.Items.Add(“Echo: “ + ee.Data);
            client.OnClose += (ss, ee) =>
               listBox1.Items.Add(string.Format(“Disconnected with {0}”, host));
        }

Upvotes: 0

ggeorge
ggeorge

Reputation: 1630

This is a general sample using ClientWebSocket class (https://learn.microsoft.com/en-us/dotnet/api/system.net.websockets.clientwebsocket?view=net-6.0)

var wsClient = new ClientWebSocket();

public async Task OpenConnectionAsync(CancellationToken token)
{
    //In case you need proxy
    wsClient.Options.Proxy = Proxy;

    //Set keep alive interval
    wsClient.Options.KeepAliveInterval = TimeSpan.Zero;

    //Set desired headers
    wsClient.Options.SetRequestHeader("Host", _host);

    //Add sub protocol if it's needed
    wsClient.Options.AddSubProtocol("zap-protocol-v1");

    //Add options if compression is needed
    wsClient.Options.DangerousDeflateOptions = new WebSocketDeflateOptions
    {
       ServerContextTakeover = true,
       ClientMaxWindowBits = 15
    };

    await wsClient.ConnectAsync(new Uri(_url), token).ConfigureAwait(false);
}

//Send message
public async Task SendAsync(string message, CancellationToken token)
{
    var messageBuffer = Encoding.UTF8.GetBytes(message);
    await wsClient.SendAsync(new ArraySegment<byte>(messageBuffer), WebSocketMessageType.Text, true, token).ConfigureAwait(false);
}

//Receiving messages
private async Task ReceiveMessageAsync(byte[] buffer)
{
    while (true)
    {
        try
        {
            var result = await wsClient.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None).ConfigureAwait(false);

           //Here is the received message as string
            var message = Encoding.UTF8.GetString(buffer, 0, result.Count);            
            if (result.EndOfMessage) break; 
         }
         catch (Exception ex)
         {
             _logger.LogError("Error in receiving messages: {err}", ex.Message);
             break;
         }
     }
}

public async Task HandleMessagesAsync(CancellationToken token)
{
    var buffer = new byte[1024 * 4];
    while (wsClient.State == WebSocketState.Open)
    {
        await ReceiveMessageAsync(buffer);
    }
    if (WsClient.State != WebSocketState.Open)
    {
         _logger.LogInformation("Connection closed. Status: {s}", WsClient.State.ToString());
         // Your logic if state is different than `WebSocketState.Open`
    }
}

Even though this is a general example of using the ws client you can figure out easily the concept and adapt it to your scenario.

Upvotes: 4

Related Questions