c# windows 形式的 Websocket 客户端连接

Websocket client connection in c# windows forms

我正在寻找使用 websocket 从服务器获取数据的方法,将它们转换为 .json 并将它们存储在 sqlite 数据库中以在 winforms 中使用过滤后的数据。我尝试了一些来自互联网的示例,但无法使它们正常工作。

试过这个 python 代码:

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

来自这个开源网站 link http://livepersoninc.github.io/ws-test-page/?

我从服务器获取数据,但我只需要在 C# 中有类似的想法。

示例 text/json 来自服务器:

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

这是使用 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`
    }
}

虽然这是使用 ws 客户端的一般示例,但您可以轻松理解概念并根据您的场景进行调整。