博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
socket测试远程地址能否连接并为连接设置超时
阅读量:6864 次
发布时间:2019-06-26

本文共 3009 字,大约阅读时间需要 10 分钟。

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;           }       }       ///        /// Socket连接请求       ///        /// 网络端点       /// 超时时间       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 ;}    }         ///         /// 接收客户端发来的信息         ///         /// 客户端套接字对象        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;                }            }                   }         }

 

转载于:https://www.cnblogs.com/bile/p/3607213.html

你可能感兴趣的文章