gpt4 book ai didi

c# - 处理关闭/断开网络套接字连接(CloseAsync 与 CloseOutputAsync)

转载 作者:太空宇宙 更新时间:2023-11-03 10:27:24 25 4
gpt4 key购买 nike

我正在尝试理解和处理关闭 Web 套接字连接的不同方式。来自 msdn :

You can use the CloseAsync and CloseOutputAsync methods for bothclient-initiated and server-initiated requests to close anAspNetWebSocket connection. The two methods handle client-initiatedrequests in the same way: After the client sends a message to theserver to close the connection, the server calls one of these methodsand sends an acknowledgment to the client, and then the methodreturns.

For server-initiated requests, the two methods workdifferently. The CloseAsync method sends a message to the client toclose the connection, waits for a response, and then returns. Theserver does not wait for any additional data sent by the client. Incontrast, the CloseOutputAsync method sends a message to the client toclose the connection and returns without waiting for a response. Afterthe method returns, you can call the ReceiveAsync method and handleeither additional data or the acknowledgment that the client sends.

在我的应用程序中,客户端基本上坐在那里从服务器接收更新,但除了打开连接之外,实际上从不向服务器发送任何内容。然而,客户端还需要能够从他们这边关闭连接。

基本上服务器的角色是坐在那里等待打开连接,发送一堆东西,并处理客户端关闭连接(但永远不必决定是否关闭连接)。

所以无论如何,当我们谈论彻底关闭连接时,客户端需要向服务器发送一条消息,说明它想要关闭连接,对吗?

所以客户端需要做这样的事情:

var x = await closeAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None)

服务端怎么知道客户端执行了closeAync?我尝试使用以下方法从服务器向客户端发送一段数据:

await sendAsync(new ArraySegment<byte>(infoBytes), 1, false, cancelled);

并收到一个错误:

"The received message type 'Text' is invalid after callingWebSocket.CloseAsync. WebSocket.CloseAsync should only be used if nomore data is expected from the remote endpoint. Use'WebSocket.CloseOutputAsync' instead to keep being able to receivedata but close the output channel."

那么在服务器端我如何知道客户端是否正在尝试干净地关闭连接?

最佳答案

在服务器端:

 var result = await webSocket.ReceiveAsync(buffer, cancellationToken);

if (result.MessageType == WebSocketMessageType.Close)
{
await webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Closed in server by the client", CancellationToken.None);
return null;
}

关于c# - 处理关闭/断开网络套接字连接(CloseAsync 与 CloseOutputAsync),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31254353/

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