Exemplo n.º 1
0
        public bool Connect(string host, int port)
        {
            if (m_Socket != null)
            {
                Debuger.LogError(LOG_TAG_MAIN, "Connect() 无法建立连接,需要先关闭上一次连接!");
                return(false);
            }

            Debuger.Log(LOG_TAG_MAIN, "Connect() 建立基础连接, host = {0}, port = {1}", (object)host, port);

            m_Host = host;
            m_Port = port;

            try
            {
                //获取Host对应的IPEndPoint
                Debuger.Log(LOG_TAG_MAIN, "Connect() 获取Host对应的IPEndPoint");
                m_HostEndPoint = UdpSocket.GetHostEndPoint(m_Host, m_Port);
                if (m_HostEndPoint == null)
                {
                    Debuger.LogError(LOG_TAG_MAIN, "Connect() 无法将Host解析为IP!");
                    Close();
                    return(false);
                }
                Debuger.Log(LOG_TAG_MAIN, "Connect() HostEndPoint = {0}", m_HostEndPoint.ToString());

                m_IsRunning = true;

                //创建Socket
                Debuger.Log(LOG_TAG_MAIN, "Connect() 创建UdpSocket, AddressFamily = {0}", m_HostEndPoint.AddressFamily);
                m_Socket = CreateSocket(m_HostEndPoint.AddressFamily, m_Host, m_Port);

                if (m_UseGSDK)
                {
                    Debuger.Log(LOG_TAG_MAIN, "Connect() 启动GSDK加速!");
                    GSDKManager.Instance.StartSpeed(m_HostEndPoint.Address.ToString(), m_Host, m_Port);

                    GSDKManager.Instance.QueryNetwork(true, true, true);
                }

                //创建线程
                Debuger.Log(LOG_TAG_MAIN, "Connect() 创建接收线程");
                m_ThreadReceive = new Thread(Thread_Receive)
                {
                    IsBackground = true
                };
                m_ThreadReceive.Start();

                Debuger.Log(LOG_TAG_MAIN, "Connect() 创建发送线程");
                m_ThreadSend = new Thread(Thread_Send)
                {
                    IsBackground = true
                };
                m_ThreadSend.Start();
            }
            catch (Exception e)
            {
                Debuger.LogError(LOG_TAG_MAIN, "Connect() " + e.Message + e.StackTrace);
                Close();
                return(false);
            }


            //统计字段
            LastRemotePort   = port;
            LastRemoteHost   = host;
            LastRemoteHostIP = m_HostEndPoint.Address.ToString();


            //当用户直接用UnityEditor上的停止按钮退出游戏时,会来不及走完整的析构流程。
            //这里做一个监听保护
#if UNITY_EDITOR
            UnityEditor.EditorApplication.playmodeStateChanged -= OnEditorPlayModeChanged;
            UnityEditor.EditorApplication.playmodeStateChanged += OnEditorPlayModeChanged;
#endif
            KHDebugerGUI.AddDbgGUI("FSPClient", OnDbgGUI);

            return(true);
        }