Home > other >  Websocket client connection in c# windows forms
Websocket client connection in c# windows forms

Time:05-03

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"}]]

CodePudding user response:

This is a general sample using ClientWebSocket class (https://docs.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 is 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.

  • Related