Tony
Tony

Reputation: 2076

.net WebSocket: CloseOutputAsync vs CloseAsync

We have a working ASP.NET Web API REST service that uses WebSockets on one of our controller's methods using HttpContext.AcceptWebSocketResponse(..).

The socket handler the code looks something like this...

public async Task SocketHandler(AspNetWebSocketContext context)
{
    _webSocket = context.WebSocket;
    ...
    while(!cts.IsCancellationRequested)
    {
        WebSocketReceiveResult result = _webSocket.ReceiveAsync(inputSegment, cts.Token).Result;
        WebSocketState currentSocketState = _webSocket.State;

        if (result.MessageType == WebSocketMessageType.Close ||
            currentSocketState == WebSocketState.CloseReceived)
        {
            // Should I use .CloseAysnc() or .CloseOutputAsync()?
            _webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "client requested", cts.Token).Wait();
        }

        if (currentSocketState == WebSocketState.Open)
        {
        ...
        }
    }
}

What is difference between .CloseAsync() and CloseOutputAysnc()? I tried both and they both seemed to work fine, but there must be some difference. They both have very similar descriptions on MSDN...

System.Net.WebSockets.CloseAsync -- Closes the WebSocket connection as an asynchronous operation using the close handshake defined in the WebSocket protocol specification section 7.

System.Net.WebSockets.CloseOutputAsync -- Initiates or completes the close handshake defined in the WebSocket protocol specification section 7.

Upvotes: 19

Views: 9779

Answers (1)

ToastyMallows
ToastyMallows

Reputation: 4273

https://www.salmanq.com/blog/5-things-you-probably-didnt-know-about-net-websockets/

...The graceful way is CloseAsync which when initiated sends a message to the connected party, and waits for acknowledgement. ...The other option is to use CloseOutputAsync this is more of a “fire-and-forget” approach. ...

It looks like you're getting a closing message;

if (result.MessageType == WebSocketMessageType.Close ||
            currentSocketState == WebSocketState.CloseReceived)

so I'd say you'd be just fine using CloseOutputAsync because you've already gotten a message that says "I want to close this connection".

Upvotes: 20

Related Questions