Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# .net WebSocket:CloseOutputAsync与CloseAsync_C#_.net_Asp.net Web Api_Websocket - Fatal编程技术网

C# .net WebSocket:CloseOutputAsync与CloseAsync

C# .net WebSocket:CloseOutputAsync与CloseAsync,c#,.net,asp.net-web-api,websocket,C#,.net,Asp.net Web Api,Websocket,我们有一个正在工作的ASP.NET Web API REST服务,该服务使用HttpContext.AcceptWebSocketResponse(..)在控制器的一个方法上使用WebSocket 代码中的套接字处理程序如下所示 public async Task SocketHandler(AspNetWebSocketContext context) { _webSocket = context.WebSocket; ... while(!cts.IsCancella

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

代码中的套接字处理程序如下所示

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()和CloseOutputAsync()之间有什么区别?我试了两种方法,两种方法似乎都很好,但肯定有些不同。他们对MSDN的描述都非常相似

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

System.Net.WebSocket.CloseOutputAsync——启动或完成WebSocket协议规范第7节中定义的闭合握手。

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

看起来你收到了一条结束信息

if (result.MessageType == WebSocketMessageType.Close ||
            currentSocketState == WebSocketState.CloseReceived)
所以我想说,您可以使用
CloseOutputAsync
,因为您已经收到一条消息,上面写着“我想关闭此连接”