随笔 - 272  文章 - 7  评论 - 27  阅读 - 83万

socket测试远程地址能否连接并为连接设置超时

复制代码
 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;
                }
            }
           
        }

     
    }
复制代码

 

posted on   NLazyo  阅读(4829)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示