.net WebSocket: CloseOutputAsync vs CloseAsync

We have a running ASP.NET Web API REST service that uses WebSockets for one of our controller methods using HttpContext.AcceptWebSocketResponse (..).

The socket handler 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 the difference between .CloseAsync () and CloseOutputAysnc ()? I tried both, and they both seemed to work fine, but there should be some difference. Both have very similar descriptions on MSDN ...

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

System.Net.WebSockets.CloseOutputAsync - initiates or terminates the closed handshake defined in section 7 of the WebSocket protocol specification.

+6
source share
1 answer

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

... An elegant way is CloseAsync, which at startup sends a message to the connected side and waits for confirmation .... Another option is to use CloseOutputAsync, it is rather a "fire and forget" approach ....

It looks like you are getting a close message;

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

therefore, I would say that everything will be fine with you using CloseOutputAsync , because you have already received a message that says: "I want to close this connection."

+8
source

Source: https://habr.com/ru/post/977727/


All Articles