Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

ReceiveAsync gives half of my WebSocket message in C#

ErrorJSON parse error on a message that looks cut off

Short answer

One ReceiveAsync call fills at most your buffer, so a message larger than the buffer arrives in several pieces. It does not wait for the whole message. Keep calling it and append each piece until WebSocketReceiveResult.EndOfMessage is true, and only then parse the text. Also never run two receives at once on one socket.

  • Applies to .NET 8, .NET 9, System.Net.WebSockets
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Log Count and EndOfMessage for every receive. If EndOfMessage is false, the message is not finished and you must read again.

    var result = await ws.ReceiveAsync(new ArraySegment<byte>(buffer), ct);
    Console.WriteLine($"count={result.Count} end={result.EndOfMessage}");
  2. 2Match what you see, then jump to its fix

    1. 1EndOfMessage is false and the text stops mid-sentence or mid-JSONThe code treats one receive as one messageFix
    2. 2Messages arrive scrambled or missing pieces, with no exceptionTwo receives run at the same time on one socketFix

What does the error look like?

  • JSON parse error on a message that looks cut off
  • result.EndOfMessage is false after the first ReceiveAsync

Cause 1 of 2

The code treats one receive as one message

1Check

Look for a single ReceiveAsync followed straight by decoding. The call completes when data has arrived on the socket, and EndOfMessage reports whether the message has been received completely. A message bigger than the buffer needs more than one call.

grep -rn "ReceiveAsync" --include=*.cs .

2Fix

Read in a loop into a MemoryStream until EndOfMessage is true. Decode only the bytes you collected, using the Count of each result.

var buffer = new byte[4096];
using var ms = new MemoryStream();
WebSocketReceiveResult result;
do
{
    result = await ws.ReceiveAsync(new ArraySegment<byte>(buffer), ct);
    ms.Write(buffer, 0, result.Count);
} while (!result.EndOfMessage);

var text = Encoding.UTF8.GetString(ms.ToArray());

3Verify

Send a message larger than the buffer from the server and confirm the decoded text is complete.

Console.WriteLine(text.Length);

Confirmed by learn.microsoft.com

Did this fix it?

Cause 2 of 2

Two receives run at the same time on one socket

1Check

Look for a second loop, a timer or a request handler that also calls ReceiveAsync on the same WebSocket object. Only one receive and one send may be in flight at a time; overlapping receives are not supported and give undefined behavior.

grep -rn "ReceiveAsync" --include=*.cs .

2Fix

Keep one receive loop per socket. If other code needs the data, pass the completed messages on through a Channel or an event, or serialize access with a SemaphoreSlim.

var channel = System.Threading.Channels.Channel.CreateUnbounded<string>();
// receive loop: await channel.Writer.WriteAsync(text);
// consumers:    await foreach (var msg in channel.Reader.ReadAllAsync()) { ... }

3Verify

Only one place in the code calls ReceiveAsync for each socket, and the messages arrive whole and in order.

grep -rn "ReceiveAsync" --include=*.cs . | wc -l

Confirmed by learn.microsoft.com

Did this fix it?

How do I stop it coming back?

  • Write one shared ReadMessageAsync helper that does the loop, and never call ReceiveAsync anywhere else.
  • Use a buffer size that fits most messages so the loop usually runs once.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Back end

ng serve says it cannot determine the project or target

Cannot determine project for command.

The Angular CLI looked through angular.json for a project that defines the target you asked for (serve, build, test) and found none, or found several and could not pick one.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.