ReceiveAsync gives half of my WebSocket message in C#
JSON parse error on a message that looks cut offShort 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.
Fix it fast
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}");2Match what you see, then jump to its fix
What does the error look like?
JSON parse error on a message that looks cut offresult.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
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 -lConfirmed by learn.microsoft.com
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
Endpoint has authorization metadata but UseAuthorization is missing
contains authorization metadata, but a middleware was not found that supports authorization.
An endpoint carries [Authorize] or RequireAuthorization, but the authorization middleware never ran for that request.
2 causes, each with a fixBack end
.NET in Docker cannot load libldap for LDAP or Active Directory
Unable to load shared library 'libldap-2.5.so.0' or one of its dependencies
On Linux, .NET's LDAP code loads the OpenLDAP library at run time, and the .NET images do not ship it.
2 causes, each with a fixBack end
Airflow SSHOperator stops a long script with SSH command timed out
airflow.exceptions.AirflowException: SSH command timed out
SSHOperator waits only 10 seconds for a command by default.
3 causes, each with a fixBack end
Android gets HTML instead of JSON from a PHP API
org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
The response body is not JSON.
2 causes, each with a fixBack 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 fixBack end
ng fails with Cannot find module @angular/cli/bin/ng
Cannot find module '@angular/cli/bin/ng'
The ng command is the entry point to the Angular CLI package.
2 causes, each with a fix