正常断开重连方法

//两秒检测一次连接是否正常
InvokeRepeating("ConnectServer",1f,2f);

 /// <summary>
    /// 连接服务器
    /// </summary>
    void ConnectServer() {
        if (client == null)
        {
            string ip = ProjectSetting.Server;
            int port = ProjectSetting.Port;
            //  socket2.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); 多socket 复用同一端口
            client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint address = new IPEndPoint(IPAddress.Parse(ip), port);
            //client.Blocking = false;
            ///建立异步连接服务 , Connected 进行监听
            client.BeginConnect(address, new AsyncCallback(Connected), null);
        }
        else if(!client.Connected)
        {
            try
            {
                client.Shutdown(SocketShutdown.Both);//禁止此Socket的接受和发送
                client.Disconnect(true);
            }
            catch (Exception)
            {
               
            }
            finally {
                Debug.Log("重新连接中。。。");
                client.Close();
                client = null;
            }
        }
    }
 
//检测服务器是否可以连接
 /// <summary>
    /// 采用Socket方式,测试服务器连接
    /// </summary>
    /// <param name="host">服务器主机名或IP</param>
    /// <param name="port">端口号</param>
    /// <param name="millisecondsTimeout">等待时间:毫秒</param>
    /// <returns></returns>
    public bool TestConnection(string host, int port, int millisecondsTimeout)
    {
        TcpClient client = new TcpClient();
        try
        {
            var ar = client.BeginConnect(host, port, null, null);
            ar.AsyncWaitHandle.WaitOne(millisecondsTimeout);
            return client.Connected;
        }
        catch (Exception e)
        {
            throw e;
        }
        finally
        {
            client.Close();
        }
    }

 

posted on 2021-10-09 18:54  陌洛  阅读(611)  评论(0编辑  收藏  举报