Socket 客户端的断开重连

因为服务端不是自己写,不能进行心跳检测,只能尝试其他方式。

在尝试其他方式失败的情况下,无奈的开始尝试增加一条线程进行连接测试,即使用一个Socket_client_test 连接服务端,然后使用disconnect(true)方式,当连接断开时抛出异常并结束线程,此时判断为断开,开始重连。

测试代码如下:

        private void client_connect_test()
        {
            string test_host = Tb_clientIP.Text;
            int test_port = Convert.ToInt32(Tb_clientPort.Text);
            IPAddress test_ip = IPAddress.Parse(test_host);
            IPEndPoint test_endPoint = new IPEndPoint(test_ip, test_port);

            try
            {
                client_test_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                client_test_socket.Connect(test_endPoint);
                Thread.Sleep(20);
                client_test_socket.Disconnect(true);  //true会将进程一直保持在这一步直到发生异常,false在重复运行时容易发生错误,暂时就没试了。。。
            }
            catch (Exception e)
            {
                log_writer("#4 远程断开,重新连接。" + e.Message);
                client_reboot_need = true;  //需重启的标志
            }
        }

 

纯粹瞎看自学,先以目的为指导,之后再看看原因了。。。

posted @ 2018-10-14 16:20  千释  阅读(1632)  评论(0编辑  收藏  举报