精确的判断网络是否可用(转贴)

[入库:2005年8月18日] [更新:2007年3月25日]

本文简介:选择自 gxh973121 的 blog

socket类的connected属性往往不能精确的判断出网络是否连接,下面这段代码可以解决这个问题

/// <summary>
/// 是否已经连接
/// </summary>
public virtual bool connected
{
 get
 {
  try
  {
   //检查socket的状态是否可读
   if(m_socket.connected && m_socket.poll(0, selectmode.selectread))
   {
    byte[] abyte = new byte[1];
    //因为tcp/ip协议无法精确的判断网络是否可用
    //试读一个字符,peek参数指定读取的字符不会从缓冲区中移除
    //假如可读则表示连接可用
    if(m_socket.receive(abyte, 0, 1, socketflags.peek) != 0)
     return true;
    close("disconnected.");
    return false;
   }
  }
  catch(socketexception e)
  {
   onexception(e);
  }
  return m_socket.connected;
 }
}

本文关键:精确的判断网络是否可用(转贴)
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top