C#TCP Socket编程 - 确定连接是否已被删除已被、TCP、Socket

2023-09-06 23:15:51 作者:怀中山河

我试图发现是否一个TCP连接在给定的时间间隔后,被丢弃在服务器上,并写了下面的code;

I am trying to discover whether a TCP connection is being dropped at the server after a given interval and have written the following code;

 var tcpClient = new TcpClient();

 tcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, true);

 tcpClient.Connect(Ip, Port);
 var status = tcpClient.Connected ? "Connected" : "Failed to Connect";

 if (connected)
 {
    Console.WriteLn(string.Format("Connected - Waiting for '{0}' to see if the connection is dropped", ConnectionDuration));
    Thread.Sleep(ConnectionDuration);
    status = tcpClient.Connected ? "Stayed Connected" : "Connection Dropped";
 }

 Console.WriteLn(string.Format("Connection Status: '{0}'", status);

通过这个code,如果是由一个连接开始我会一直收到沉祥福连接状态消息。

With this code, if a connection is made initially I will always receive the "Stayed connected" status message.

由于服务器是我们公司之外它不是理想的数据写入套接字,还有没有其他的方法来确定连接已断开?

Because the server is outside our company it's not desirable to write data to the socket, is there any other way to determine if the connection has been dropped?

感谢

推荐答案

请非阻塞零字节发送调用,如果你得到一个WOULDBLOCK错误code或成功,你仍然连接。

Make a non-blocking zero byte Send call, if you get a WOULDBLOCK error code or success, you are still connected.