如何判断基于套接字的客户端中的连接是否已断开? [英] How can I tell if the connection has been broken in my sockets based client?

查看:36
本文介绍了如何判断基于套接字的客户端中的连接是否已断开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的客户端的连接在另一个 end(kill -9 server) 上断开.客户端需要几分钟才能确定出现问题.Socket.Connected 返回 true,即使连接实际上已断开.

If my client's connection is broken on the other end( kill -9 server). It takes several minutes for the client to determine that something is wrong. Socket.Connected returns true even though connection is actually broken.

一旦另一端断开链接,确定连接不存在的最快方法是什么?

What is the fastest way to determine that the connection doesn't exist, once the other end breaks the link?

try{
      Socket socket= new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     /*Assume there is a connection on the other end*/
      while (socket.Connected)
      {
    
          /*Do some processing*/
      }
 }catch (SocketException se){
       Console.WriteLine(ex.Message);
 } catch (Exception ex){
       Console.WriteLine(ex.Message);
 }
 finally
 {
   Console.WriteLine("something bad happen");
 }

推荐答案

这似乎对我有用... 有人看到任何问题吗?

This seems to work for me... Does anyone see any issues?

public bool IsConnected
{
         get {return !(Socket.Poll(1, SelectMode.SelectRead) 
                                  && m_socket.Available ==0)}
}

<小时>

也可以放入扩展方法中.


Can also be put into an extension method.

public static class SocketExtensions
{
  public static bool IsConnected(this Socket @this)
  {
    return !(@this.Poll(1, SelectMode.SelectRead) && @this.Available == 0);
  }
}

现在您可以在处理套接字的代码中轻松使用它.

Now you can easily use it in your code dealing with sockets.

var mySocket = new Socket();
while(mySocket.IsConncted())
{
  // Do Stuff
}

这篇关于如何判断基于套接字的客户端中的连接是否已断开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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