[英]C# TcpClient - What's the best way for a client to determine if remote server has gracefully shutdown connection?
I know there are various suggested ways to achieve this, using Poll/Available/Send, etc., but none of them seem to work for me.我知道有各种建议的方法来实现这一点,使用 Poll/Available/Send 等,但它们似乎都不适合我。 I have a connection to a remote server, which the remote server gracefully disconnects after a specific message.
我有一个到远程服务器的连接,远程服务器在收到特定消息后会优雅地断开连接。 I need to ensure I don't disconnect from the remote server myself, and wait for the server to shutdown connection before I can safely reconnect and send other follow-up messages.
我需要确保自己不会断开与远程服务器的连接,并等待服务器关闭连接,然后才能安全地重新连接并发送其他后续消息。
I'm using the ReadAsync method on Stream to get responses from that connection, as below:我在 Stream 上使用 ReadAsync 方法从该连接获取响应,如下所示:
while (await TcpClientObject.GetStream().ReadAsync(bufferData, 0, bufferData.Length) > 0)
{
//My logic here to handle responses
}
What's the most recommended approach for me to verify that the remote server has gracefully shutdown the connection before attempting a reconnect?在尝试重新连接之前,我最推荐的验证远程服务器是否已正常关闭连接的方法是什么? Thanks.
谢谢。
If everything goes well ReadAsync
will return 0 when the server closes the connection.如果一切顺利,
ReadAsync
将在服务器关闭连接时返回 0。
An exception is thrown if your side detects an abnormal disconnection, but in the worst case your end still thinks it's connected and ReadAsync
won't return.如果您的一方检测到异常断开连接,则会引发异常,但在最坏的情况下,您的一方仍然认为它已连接并且
ReadAsync
不会返回。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.