C#TCP Socket编程 - 确定连接是否已被删除 [英] C# TCP Socket Programming - Determining whether a connection has been dropped

查看:643
本文介绍了C#TCP Socket编程 - 确定连接是否已被删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图发现是否一个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.

这篇关于C#TCP Socket编程 - 确定连接是否已被删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆