.net WebSocket:CloseOutputAsync与CloseAsync [英] .net WebSocket: CloseOutputAsync vs CloseAsync

查看:193
本文介绍了.net WebSocket:CloseOutputAsync与CloseAsync的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个有效的ASP.NET Web API REST服务,该服务在使用HttpContext.AcceptWebSocketResponse(..)的控制器方法之一上使用WebSockets.

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)
        {
        ...
        }
    }
}

.CloseAsync()和CloseOutputAysnc()有什么区别?我都尝试过,但它们似乎都可以正常工作,但必须有所区别.他们在MSDN上都有非常相似的描述...

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 -使用WebSocket协议规范第7节中定义的关闭握手,作为异步操作关闭WebSocket连接.

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 -启动或完成WebSocket协议规范第7节中定义的关闭握手.

System.Net.WebSockets.CloseOutputAsync -- Initiates or completes 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/

...优雅的方法是CloseAsync,当启动时,它会向连接的一方发送一条消息,并等待确认....另一个选择是使用CloseOutputAsync,这更像是一劳永逸"的方法....

...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)

所以我说您使用 CloseOutputAsync 会很好,因为您已经收到一条消息,内容为我想关闭此连接".

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".

这篇关于.net WebSocket:CloseOutputAsync与CloseAsync的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆