You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The Listen method is not properly using _webSocket.ReceiveAsync.
You're getting bad JSON because you're not checking result.EndOfMessage. So you're getting a partial message and then the "leftovers" are the things you're trying to "trim".
Below is an example solution.
private async Task Listen()
{
ArraySegment<Byte> buffer = new ArraySegment<byte>(new Byte[1024]);
WebSocketReceiveResult result = null;
while (_webSocket.State == WebSocketState.Open)
{
using (var ms = new MemoryStream())
{
do
{
result = await _webSocket.ReceiveAsync(buffer, CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
break;
}
else
{
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))
{
var stringData = await reader.ReadToEndAsync();
#if DEBUG
Console.WriteLine($"Receive: {stringData}");
#endif
OnMessage?.Invoke(this, stringData);
}
}
}
}
}
The text was updated successfully, but these errors were encountered:
The
Listen
method is not properly using_webSocket.ReceiveAsync
.You're getting bad JSON because you're not checking
result.EndOfMessage
. So you're getting a partial message and then the "leftovers" are the things you're trying to "trim".Below is an example solution.
The text was updated successfully, but these errors were encountered: