在C#中检测TCP或Socket中的连接状态 [英] Detect Connection status in TCP or Socket at C#

查看:2625
本文介绍了在C#中检测TCP或Socket中的连接状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

我正在使用VS2008和c#..网络概念..我想从服务器中的客户端获取状态..而客户端与服务器断开连接意味着状态将来到服务器...断开意味着断电,按下关闭或重新启动cpu ..

I'm using VS2008 and c#.. Networking Concept.. i want to do get status from client in server.. while client disconnected from server means status will come to server ... disconnected means power down, press turn off or restart in cpu..

PLZ帮我解决问题....

plz help me for my solutions....

如果有可能做到这一点.....

if any possible to do this .....

 

推荐答案

尝试使用Socket.Connected属性。

Hi, try to use Socket.Connected property.

如果你想获得状态"断开连接",你还有试图发送一些东西。只能在发送数据时确定连接状态。如果在发送数据时连接断开,则会出现异常。否则,您
将不会收到任何通知。您可以设计协议以定期发送"保持活动"状态。消息,但这通常不是正确的做法。在您真正尝试使用它之前,TCP不会检测到断开的连接是一件好事。这样可以在不影响连接的情况下发生
瞬态问题。 

If you want to get the status "Disconnected", you still have to try to send something. Connection status can only be determined when you send data. If the connection is broken when you send data, you'll get an exception. Otherwise, you won't receive any notification. You can design your protocol to send periodic "keep alive" messages, but that's not usually the right thing to do. It's a _good_ thing that TCP doesn't detect a broken connection until you actually try to use it. That allows transient problems to occur without affecting your connection. 

使用Socket.Connected的示例

AN Example of using Socket.Connected


// .Connect throws an exception if unsuccessful
client.Connect(anEndPoint);

// This is how you can determine whether a socket is still connected.
bool blockingState = client.Blocking;
try
{
 byte [] tmp = new byte[1];

 client.Blocking = false;
 client.Send(tmp, 0, 0);
 Console.WriteLine("Connected!");
}
catch (SocketException e) 
{
 // 10035 == WSAEWOULDBLOCK
 if (e.NativeErrorCode.Equals(10035))
  Console.WriteLine("Still Connected, but the Send would block");
 else
 {
  Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode);
 }
}
finally
{
 client.Blocking = blockingState;
}

 Console.WriteLine("Connected: {0}", client.Connected);


这篇关于在C#中检测TCP或Socket中的连接状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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