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.
close() The WebSocket. close() method closes the WebSocket connection or connection attempt, if any. If the connection is already CLOSED , this method does nothing.
In addition, WebSockets is only supported on Windows 8 and Windows Server 2012. This means that you can develop on Windows 7 or earlier OS versions, but your ASP.NET or WCF WebSocket services will only work on Windows 8 or Windows Server 2012.
WebSocket (RFC 6455) is a protocol that enables two-way persistent communication channels over TCP connections. It's used in apps that benefit from fast, real-time communication, such as chat, dashboard, and game apps. View or download sample code (how to download).
In this article. Closes the WebSocket connection as an asynchronous operation using the close handshake defined in the WebSocket protocol specification section 7.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With