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

后端 未结 5 2087
借酒劲吻你
借酒劲吻你 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:02

    Just to complete @Noseratio response, the code would be something like this:

    ArraySegment buffer = new ArraySegment(new Byte[8192]);
    
    WebSocketReceiveResult result= null;
    
    using (var ms = new MemoryStream())
    {
         do
         {
             result = await socket.ReceiveAsync(buffer, CancellationToken.None);
             ms.Write(buffer.Array, buffer.Offset, result.Count);
         }
         while (!result.EndOfMessage);
    
         ms.Seek(0, SeekOrigin.Begin);
    
         if (result.MessageType == WebSocketMessageType.Text)
         {
              using (var reader = new StreamReader(ms, Encoding.UTF8))
              {
                   // do stuff
              }
         }
    }
    

    Cheers.

提交回复
热议问题