gpt4 book ai didi

c# - 在 asp.net 核心服务器中处理关闭的 websocket 连接

转载 作者:太空狗 更新时间:2023-10-30 01:30:36 24 4
gpt4 key购买 nike

任何人都可以向我解释如何从意外终止连接的客户端中删除 websockets 吗?我的意思是用户以错误的方式关闭了应用程序,没有告诉服务器他们想要断开连接?以及您通常如何处理断开连接。

我尝试了一段代码来监听消息接收并且有一个带有 3s 的 cancellationTokenSource,所以它将检查连接是否仍然存在。当我关闭 websocket 客户端应用程序时,服务器不会转到 WebSocketState.Closed 部分,并且当取消 token 被触发时,服务器会断开与客户端的连接。我在这里做错了什么?!提前致谢!

while (socket.State == WebSocketState.Open)
{
var cancellationSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(3000));
buffer = new ArraySegment<byte>(new byte[4096]);

WebSocketReceiveResult received = null;


try
{
received = await socket.ReceiveAsync(buffer, cancellationSource);
}
catch (AggregateException e)
{
continue;
}

switch (received.MessageType)
{
case WebSocketMessageType.Close:

HandleClose(socket);

break;

case WebSocketMessageType.Text:
// Handle text message

break;
}
}

if (socket.State == WebSocketState.Aborted)
{
// Handle aborted
}
else if (socket.State == WebSocketState.Closed)
{
HandleClose(socket);
}
else if (socket.State == WebSocketState.CloseReceived)
{

}
else if (socket.State == WebSocketState.CloseSent)
{
}

最佳答案

如果客户端意外关闭连接,ReceiveAsync 将抛出一个 WebSocketException

try
{
var received = await webSocketConnection.ReceiveAsync(...);
}
catch(WebSocketException webSocketException)
{
if(webSocketException.WebSocketErrorCode == WebSocketError.ConnectionClosedPrematurely)
{
//custom logic
}
}

关于c# - 在 asp.net 核心服务器中处理关闭的 websocket 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44312881/

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