C#Socket客户端如何自动连接并传输数据

C#Socket客户端如何自动连接并传输数据

      • 留言

2020/6/15 21:25
代码片.

 //与服务器连接
        private void ConnectServerAutoSend()
        {
            //开启线程
            thread = new Thread(AutoConnect);
            thread.IsBackground = true;
            thread.Start();
        }
            //线程调用自动连接方法
        private void AutoConnect()
        {
            while (true)
            {
                Thread.Sleep(5000);
                //创建Socket套接字对象
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //开启异步连接
                socket.BeginConnect(point2, asyncCallback, 0);
                //判断是否连接,否关闭套接字
                if (!TestConnection("192.168.43.70", 23456) & !socket.Connected)
                {
                    socket.Close();
                }
                //5s自动判断是否连接
                else if (socket.Connected)
                {
                    while (true)
                    {
                        Thread.Sleep(5000);
                 //连接异常跳出循环,重新创建创建套接字循环
                        if (!socket.Connected)
                        {
                            break;
                        }
                    }
                }
            }

        }
         //Socket异步连接调用方法
        private void asyncCallback(IAsyncResult ar)
        {
            while (true & socket.Connected)
            {
                Thread.Sleep(1000);
                try
                {
                    socket.Send(Encoding.UTF8.GetBytes(strDatas));
                }
                catch (Exception)
                {
                    socket.Close();
                }
            }
        }
         #region 采用Socket方式,测试服务器连接
        /// 
        /// 采用Socket方式,测试服务器连接
        /// 
        /// 服务器主机名或IP
        /// 端口号
        /// 等待时间:毫秒
        /// 
        public static bool TestConnection(string host, int port)
        {

            TcpClient client = new TcpClient();
            try
            {
                var ar = client.BeginConnect(host, port, null, null);
                ar.AsyncWaitHandle.WaitOne(5000);
                return client.Connected;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                client.Close();
            }
        }
        #endregion

留言

初入C#小白一名,不对的地方欢迎指出留言,共同进步。

你可能感兴趣的:(C#Socket客户端如何自动连接并传输数据)