socket測試遠端地址能否連線併為連線設定超時

weixin_34377065發表於2014-03-18
 public   class TestConnect
    {
        string hostIp = "";
        int port = 3314;
        public string recMsg = "";
        Socket socketC = null;
        private readonly ManualResetEvent TimeoutObject = new ManualResetEvent(false);
       public TestConnect(string hostIp, int port)
       {

           this.hostIp = hostIp;
           this.port = port;
       }
       public bool connect()
       {
           ///建立終結點(EndPoint)
           IPAddress ip = IPAddress.Parse(hostIp);//把ip地址字串轉換為IPAddress型別的例項
           IPEndPoint ipe = new IPEndPoint(ip, port);//用指定的埠和ip初始化IPEndPoint類的新例項
           ///建立socket
           socketC = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//建立一個socket對像,如果用udp協議,則要用SocketType.Dgram型別的套接字
           try
           {
               
             

               return Connect(ipe,3000);

           }

           catch (SocketException ex)
           {

               socketC.Close();
               socketC = null;
            
               return false;
           }

       }
       /// <summary>

       /// Socket連線請求

       /// </summary>

       /// <param name="remoteEndPoint">網路端點</param>

       /// <param name="timeoutMSec">超時時間</param>

       public bool Connect(IPEndPoint remoteEndPoint, int timeoutMSec)
       {

           TimeoutObject.Reset();

           socketC = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

           socketC.BeginConnect(remoteEndPoint, CallBackMethod, socketC);

           //阻塞當前執行緒

           if (TimeoutObject.WaitOne(timeoutMSec, false))
           {
              

               return true;

           }

           else
           {

               return false;

           }

       }

       //--非同步回撥方法

       private void CallBackMethod(IAsyncResult asyncresult)
       {

           //使阻塞的執行緒繼續
           Socket socket = asyncresult.AsyncState as Socket;

           if (socket.Connected)
            {
                socket.EndConnect(asyncresult);
               
            }

           TimeoutObject.Set();

       }
       public void testOnline(string msg)
       {
              socketC.Send(Encoding.GetEncoding("gb2312").GetBytes(msg));

      try

      {
          //建立一個通訊執行緒 
                ParameterizedThreadStart pts = new ParameterizedThreadStart(ServerRecMsg);
                Thread thr = new Thread(pts);
                thr.IsBackground = true;
                //啟動執行緒
                thr.Start(socketC);
      }

      catch

      { throw ;}

    }

  
    
   /// <summary>
        /// 接收客戶端發來的資訊 
        /// </summary>
        /// <param name="socketClientPara">客戶端套接字物件</param>
        private void ServerRecMsg(object socketClientPara)
        {
            Socket socketServer = socketClientPara as Socket;
            byte[] arrServerRecMsg = new byte[100];
            int len;
            while ((len = socketServer.Receive(arrServerRecMsg)) != 0)
            {

                //將機器接受到的位元組陣列轉換為人可以讀懂的字串
                recMsg = Encoding.Default.GetString(arrServerRecMsg, 0, len);


                if (recMsg == "online")
                {
                    break;
                }
            }
           
        }

     
    }

 

相關文章