【问题标题】:.net WebSocket: CloseOutputAsync vs CloseAsync.net WebSocket:CloseOutputAsync 与 CloseAsync
【发布时间】:2014-12-31 21:22:30
【问题描述】:

我们有一个有效的 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 节中定义的关闭握手。

【问题讨论】:

    标签: c# .net asp.net-web-api websocket


    【解决方案1】:

    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,因为你已经收到一条消息,上面写着“我想关闭这个连接”。

    【讨论】:

    猜你喜欢
    • 2011-04-09
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多