Skip to content

Instantly share code, notes, and snippets.

@rogeralsing
Last active January 15, 2023 13:48
Show Gist options
  • Save rogeralsing/c41f68923d2de898fa7468b3d1e59f04 to your computer and use it in GitHub Desktop.
Save rogeralsing/c41f68923d2de898fa7468b3d1e59f04 to your computer and use it in GitHub Desktop.
private static async ValueTask<ReadOnlyMemory<byte>> ReceiveStringAsync(WebSocket socket, CancellationToken ct = default)
{
var buffer = ArrayPool<byte>.Shared.Rent(128); //use shared?
using var ms = new MemoryStream(); //is there a better way here, w/o memstream?
WebSocketReceiveResult result;
do
{
ct.ThrowIfCancellationRequested();
result = await socket.ReceiveAsync(buffer, ct);
ms.Write(buffer, 0, result.Count);
} while (!result.EndOfMessage);
ms.Seek(0, SeekOrigin.Begin);
if (result.MessageType != WebSocketMessageType.Text || result.Count.Equals(0))
{
throw new Exception("Unexpected message");
}
return ms.ToArray(); //this is not great
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment