繁体   English   中英

.net WebSocket:CloseOutputAsync 与 CloseAsync

[英].net WebSocket: CloseOutputAsync vs CloseAsync

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

代码看起来像这样的套接字处理程序......

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上都有非常相似的描述......

System.Net.WebSockets.CloseAsync -- 使用 WebSocket 协议规范第 7 节中定义的关闭握手将 WebSocket 连接作为异步操作关闭。

System.Net.WebSockets.CloseOutputAsync——发起或完成在 WebSocket 协议规范第 7 节中定义的关闭握手。

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

...优雅的方式是 CloseAsync,它在启动时向连接方发送消息,并等待确认。 ...另一种选择是使用 CloseOutputAsync,这更像是一种“即发即忘”的方法。 ...

看起来您收到了结束消息;

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

所以我会说你使用CloseOutputAsync就好了,因为你已经收到一条消息,说“我想关闭这个连接”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM