A websocket's ReceiveAsync method does not await the entire message

后端 未结 5 2080
借酒劲吻你
借酒劲吻你 2020-12-05 11:45

I am receiving JSON through a websocket. At least: I am partially. Using an online websocket service I receive the full JSON response (all the HTML markup is ignored). When

5条回答
  •  悲哀的现实
    2020-12-05 12:11

    // Read the bytes from the web socket and accumulate all into a list.
    var buffer = new ArraySegment(new byte[1024]);
    WebSocketReceiveResult result = null;
    var allBytes = new List();
    
    do
    {
        result = await webSocket.ReceiveAsync(buffer, CancellationToken.None);
        for (int i = 0; i < result.Count; i++)
        {
            allBytes.Add(buffer.Array[i]);
        }
    }
    while (!result.EndOfMessage);
    
    // Optional step to convert to a string (UTF-8 encoding).
    var text = Encoding.UTF8.GetString(allBytes.ToArray(), 0, allBytes.Count);
    

提交回复
热议问题