我如何才能知道连接是否在我的插座被打破的客户端? [英] How can I tell if the connection has been broken in my sockets based client?

查看:135
本文介绍了我如何才能知道连接是否在我的插座被打破的客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的客户的连接在另一破结束(杀-9服务器)。它需要几分钟的客户端,以确定什么是错的。 Socket.Connected 即使连接实际上是打破返回true。

什么是确定的连接不存在以最快的方式,一旦另一端打破了链接?

客户端code:

 尝试{
      Socket套接字=新的Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
     / *假定有在另一端的连接* /
      而(socket.Connected)
      {

          / *做一些处理* /
      }
 }赶上(SocketException SE){
       Console.WriteLine(ex.Message);
 }赶上(例外前){
       Console.WriteLine(ex.Message);
 }
 最后
 {
   Console.WriteLine(坏事发生);
 }
 

解决方案

这似乎为我工作......没有人看到任何问题?

 公共BOOL IsConnected
{
         {返回!(Socket.Poll(1,SelectMode.SelectRead)
                                  &功放;&安培; m_socket.Available == 0)}
}
 


也可以放入扩展方法。

 公共静态类SocketExtensions
{
  公共静态布尔IsConnected(此Socket @this)
  {
    返回(@ this.Poll(1,SelectMode.SelectRead)及和放大器; @ this.Available == 0)!;
  }
}
 

现在您可以轻松地使用它在你的code处理插座。

  VAR mySocket =新的Socket();
而(mySocket.IsConncted())
{
  //做的东西
}
 

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?

Client code:

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天全站免登陆