gpt4 book ai didi

c# - .net WebSocket : CloseOutputAsync vs CloseAsync

转载 作者:太空狗 更新时间:2023-10-29 18:28:59 26 4
gpt4 key购买 nike

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

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

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 协议(protocol)规范第 7 节中定义的关闭握手作为异步操作关闭 WebSocket 连接。

System.Net.WebSockets.CloseOutputAsync -- 启动或完成 WebSocket 协议(protocol)规范第 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. ...

您似乎收到了关闭消息;

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

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

关于c# - .net WebSocket : CloseOutputAsync vs CloseAsync,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26744420/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com