How to decode websocket connection as json stream?

My client connects to the websocket server and all messages are in json format. I am using ClientWebSocket and ReceiveAsync as documented. My reading cycle looks something like this:

byte[] data = new byte[4096];
ArraySegment<byte> buffer = new ArraySegment<byte>(data);
readLoopTask = Task.Run(async () =>
{
    while (true)
    {
        var result = await socket.ReceiveAsync(buffer, CancellationToken.None);
        if (result.Count > 0)
        {
            string m = Encoding.ASCII.GetString(data, 0, result.Count);
            ProcessMessage(m); // decode json string
        }
        else
        {
            Console.WriteLine("recved zero:", result);
            break;
        }
    }
}, token);

The problems that I found with this implementation are that some of the json objects that the server passed are very large and do not fit in the buffer, in which case the read input is truncated and is not a valid json string, so decoding fails .

, websocket , json, json , json string. , json.

, WebSocket , TcpClient.GetStream, TcpClient, , json-:

Stream stream = tcpClient.GetStream();
JsonDecoder decoder = new JsonDecoder(stream);
Object obj;
while (true) {
    decoder.Decode(obj);
    // handle obj
}

, , , API ?

+3
1

, , , , . ClientWebSocket.ReceiveAsync WebSocketReceiveResult, EndOfMessage, , , , , , json-.

WebSocketReceiveResult result = null;
while(running) {
    do {
        result = await socket.ReceiveAsync(buffer, cts.Token).ConfigureAwait(false);
        if (result.Count > 0)
        {
             memStream.Write(buffer.Array, buffer.Offset, result.Count);
        }
        else
        {
             logger.LogWarning("WS recved zero: {0}, {1}", result.Count, socket.State);
             break;
        }
    } while (!result.EndOfMessage); // check end of message mark
}
0

Source: https://habr.com/ru/post/1693869/


All Articles