skip to content

In an ASP.NET Core raw WebSocket handler, how should the receive loop assemble messages and finish the close handshake cleanly?

level: middleimportance: must knowfreq 50%

answer

  1. one receive call is not one message
  2. WebSocketReceiveResult.EndOfMessage
  3. MessageType == WebSocketMessageType.Close
  4. CloseAsync vs CloseOutputAsync
  5. catch WebSocketException on abrupt drops

basics

~10 s

Loop on ReceiveAsync into a buffer, appending Count bytes until EndOfMessage, then handle the message. When MessageType is Close, answer with CloseAsync and exit; an abrupt disconnect surfaces as a WebSocketException to catch.

solid answer

~40 s

`ReceiveAsync(ArraySegment<byte>, CancellationToken)` returns a `WebSocketReceiveResult` with `Count`, `EndOfMessage`, `MessageType`, `CloseStatus` and `CloseStatusDescription`. One call fills at most your buffer, so a bid message may take several calls: append `Count` bytes until `EndOfMessage` is true, then process it, and cap the total yourself because the API does not. When `MessageType` is `WebSocketMessageType.Close`, the client started closing: reply with `CloseAsync(result.CloseStatus ?? NormalClosure, result.CloseStatusDescription, ct)` and leave the loop. When the server closes first, `CloseOutputAsync` sends its close frame without waiting, and the loop keeps receiving until the client's close arrives; `CloseAsync` sends and waits. Keep one `ReceiveAsync` outstanding at a time, never send a Close type through `SendAsync`, and catch `WebSocketException`, which is how a dropped connection shows up.

code

csharp · 23 lines
csharp
static async Task ReceiveBidsAsync(WebSocket socket, CancellationToken ct)
{
    var buffer = new byte[4 * 1024];
    using var message = new MemoryStream();

    while (socket.State == WebSocketState.Open)
    {
        var result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), ct);

        if (result.MessageType == WebSocketMessageType.Close)
        {
            await socket.CloseAsync(result.CloseStatus ?? WebSocketCloseStatus.NormalClosure,
                result.CloseStatusDescription, ct);
            return;
        }

        message.Write(buffer, 0, result.Count);
        if (!result.EndOfMessage) continue;          // more of this bid is coming

        await HandleBidAsync(message.ToArray(), result.MessageType, ct);
        message.SetLength(0);                         // start the next message
    }
}

go deeper

for a junior

Know that ReceiveAsync returns a WebSocketReceiveResult and that a Close message type means the client wants to end the connection.

for a middle

Write the loop: accumulate Count bytes until EndOfMessage, reply to Close with CloseAsync, and explain the difference between CloseAsync and CloseOutputAsync.

for a senior

Cover the production edges: a message-size cap, one outstanding receive, keeping a receive pending for control traffic, and treating WebSocketException from dropped clients as routine.

for a principal

Decide where message framing and validation live for a raw-socket protocol and whether owning that code beats adopting a library that already handles it.

## The loop is the protocol Once `AcceptWebSocketAsync` returns, ASP.NET Core gives you a `System.Net.WebSockets.WebSocket` and steps aside. Nothing reads for you, nothing reassembles messages for you, and nothing answers the client's close for you. The **receive loop** is where all of that happens, and its shape is what interviewers ask you to write on a whiteboard. ## What one ReceiveAsync call gives you `ReceiveAsync(ArraySegment<byte> buffer, CancellationToken ct)` waits for data and returns a `WebSocketReceiveResult`: - **`Count`** - how many bytes were written into your buffer this time. - **`EndOfMessage`** - `true` when those bytes finish the current message. - **`MessageType`** - `Text`, `Binary`, or `Close`. - **`CloseStatus`** / **`CloseStatusDescription`** - set when `MessageType` is `Close`. The key point: **one call is not one message.** A message larger than your buffer, or one the client sent in pieces, arrives across several calls. You append `Count` bytes each time and only treat the data as a message when `EndOfMessage` is `true`. The API sets no maximum message size, so a client can make you buffer without limit; enforce your own cap and close the socket with an error status when it is exceeded. ## Closing: who starts matters A clean WebSocket ends with a close handshake: each side sends a close message. The .NET API gives you two methods and a state machine (`WebSocketState`): | Situation | Call | What it does | State after | |---|---|---|---| | Client closed first (`MessageType == Close`) | `CloseAsync(status, description, ct)` | sends your close and completes the handshake | `Closed` | | Server wants to stop, will keep reading | `CloseOutputAsync(status, description, ct)` | sends your close frame, does not wait | `CloseSent`, then `Closed` when the client's close is received | | Server wants to stop and wait | `CloseAsync(status, description, ct)` | sends your close and waits for the client's | `Closed` | Echoing `result.CloseStatus` back (falling back to `WebSocketCloseStatus.NormalClosure`) is the conventional reply. Do **not** try `SendAsync` with `WebSocketMessageType.Close`; closing is only done through the two close methods. ## Rules for a correct loop 1. **Loop while `socket.State == WebSocketState.Open`** and leave when a Close arrives. 2. **Keep exactly one receive outstanding.** The `WebSocket` type supports one pending receive and one pending send at a time; a second concurrent `ReceiveAsync` is a bug. If several components want to send, serialise them (see the broadcasting pattern). 3. **Keep a receive pending even if you never expect client data.** Incoming control traffic (the client's close, pong replies for `KeepAliveTimeout`) is only processed while a `ReceiveAsync` is waiting. 4. **Catch `WebSocketException`.** A client that vanishes without a close handshake makes the pending receive throw (for example with `WebSocketError.ConnectionClosedPrematurely`). That is an expected outcome on mobile networks, not a server bug; log it at a low level and clean up. 5. **Dispose the socket** (a `using` around the accepted socket) and return from the handler so the request completes. ## The send side of the same socket Sending mirrors receiving. `SendAsync(buffer, WebSocketMessageType.Text, endOfMessage: true, ct)` sends one complete message; passing `endOfMessage: false` lets you stream a large message in pieces, finishing with a call whose flag is `true`. Text messages must be UTF-8, so encode strings with `Encoding.UTF8.GetBytes` before sending. Two rules carry over from the receive side: - only **one** `SendAsync` may be in flight on a socket, so if several parts of the app send, they need a single writer; - check `socket.State` before sending after a close has started; once you have sent your close (`CloseSent`), sending data is no longer allowed. ## Handing messages on Inside the loop, decode only complete messages: UTF-8 for `Text`, your own format for `Binary`. For the auction feed, a bidder's message might be a JSON bid that you validate and pass to the auction service; the broadcast of the new high bid to every other bidder happens on the send side, not inside this receive call. ## Why interviewers ask this The bugs here are silent in a demo and loud in production: treating each `ReceiveAsync` as a full message corrupts large payloads only occasionally; forgetting to answer `Close` leaves clients waiting for a handshake that never completes; not catching `WebSocketException` fills logs with "unhandled" errors every time a phone loses signal.

  • Why can a server-initiated CloseOutputAsync be followed by more ReceiveAsync calls?
    `CloseOutputAsync` only sends the server's close frame and moves the socket to `CloseSent`. The client may still have data in flight, and its own close has not arrived yet. Continuing to call `ReceiveAsync` drains that data and eventually returns a result whose `MessageType` is `Close`, after which the state is `Closed` and the handshake is complete. `CloseAsync` does that waiting for you.
  • How large should the receive buffer be?
    It is a performance knob, not a message limit: a 4 KB buffer handles a 1 MB message in many calls, which is fine. Size it for your typical message so most arrive in one call, and enforce the real message limit separately by counting accumulated bytes. `WebSocketOptions.ReceiveBufferSize` is obsolete and has no effect, so the buffer you pass to `ReceiveAsync` is the only one you control.

  • Each ReceiveAsync call returns exactly one complete message.
  • Send a WebSocketMessageType.Close message through SendAsync to close the socket.
  • When the client sends Close, just return; ASP.NET Core answers the close for you.
  • Raise WebSocketOptions.ReceiveBufferSize so whole messages fit in one receive.
  • Run two ReceiveAsync calls in parallel to read faster.
  • A WebSocketException in the receive loop always means a server bug.