简体   繁体   English

C# TcpClient - 客户端确定远程服务器是否正常关闭连接的最佳方法是什么?

[英]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.

相关问题 在 C# 控制台应用程序中保持 ActiveMQ 侦听器处于活动状态并在关闭之前优雅地处理资源的正确方法是什么? - What is the proper way to keep an ActiveMQ listener alive in a C# console application & gracefully dispose of resources prior shutdown? C#配置TCPClient客户端的端口 - C# configuring TCPClient client's port 与远程主机的连接和应用程序冻结后,TcpClient挂起C# - TcpClient hangs after connection to remote host & application freezes c# 在c#中确定程序员是通过IDE还是用户运行程序的最佳方法是什么? - What is the best way in c# to determine whether the programmer is running the program via IDE or it's user? C#将多个值从TcpClient发送到远程服务器 - C# send multiple values from TcpClient to remote server 处理C#服务器的最佳方法是什么? - What is the best way to handle a C# server? C#中的TcpClient连接尝试 - TcpClient connection attempts in C# TcpClient 与服务器通信以在 C# 中保持活动连接? - TcpClient communication with server to keep alive connection in c#? 在C#中,确定小数是否为“ int”的最佳方法是什么? - In C#, what is the best way to determine if a decimal “is an int”? 在 C# 中确定会话变量为 null 或为空的最佳方法是什么? - What is the best way to determine a session variable is null or empty in C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM