/// <summary> /// 建立连接 /// </summary> /// <returns></returns> public IEnumerator Connect() { currentStatus = ConnectStatus.CONNECTING; if (_socket != null && _socket.Connected) { Close(); } if (!firstConnect) { ShowLoadingBar(); } reader = null; _sendBuffer.CleanALL(); lock (lockObj) { _receiveList.Clear(); } isConnectCallback = false; IPAddress[] ips = Dns.GetHostAddresses(_ip); if (ips == null || ips.Length <= 0) { ProcessConectionError(Error.TIMEOUT, "Dns.GetHostAddresses Fail!"); yield break; } IPAddress _ipAddr = IPAddress.Parse(_ip); AddressFamily addressFamily = AddressFamily.InterNetwork; #if UNITY_IOS && !UNITY_EDITOR _ip = IphoneUtility.ConvertIPAddress_IOS(_ip, _port.ToString()); if (_ip.Contains(":")) { addressFamily = AddressFamily.InterNetworkV6; } else { addressFamily = AddressFamily.InterNetwork; } #else addressFamily = AddressFamily.InterNetwork; #endif //_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp); IAsyncResult ar = _socket.BeginConnect(_ip, _port, ConnectCallback, null); beginConnectElapsed = 0f; while (!ar.IsCompleted) { if (beginConnectElapsed > beginConnectTimeout) { ProcessConectionError(Error.TIMEOUT, "Network Module Initialization Fail!"); yield break; } beginConnectElapsed += Time.deltaTime; yield return(null); } while (isConnectCallback == false) { yield return(null); } if (_socket == null || !_socket.Connected) { ProcessConectionError(Error.DISCONNECTED, "Can't Connect Remote Server!"); yield break; } _reconnectNum = 1; /*PublicMatchData.MAX_RECONNECT_COUNT;*/ _retryNum = 1; /*PublicMatchData.MAX_RETRY_NUM;*/ reader = new CHSocketReader(_socket, ReadFailed, this); #region 验证 //try //{ // int sent = _socket.Send(GetLoginSendByte(), SocketFlags.None); // if (sent < 0) // { // throw new Exception("Socket sent return " + sent); // } //} //catch (Exception e) //{ // int errorCode = 0; // if (e is SocketException) // { // errorCode = (e as SocketException).ErrorCode; // } // Debug.LogWarning("!!!Socket login auth, send Error msg: " + e.Message + " |||Error code:" + errorCode); // ProcessConectionError(Error.LOGIN_FAIL, "Can't Connect Remote Server!"); // yield break; //} #endregion if (!firstConnect) { HideLoadingBar(); } firstConnect = false; currentStatus = ConnectStatus.CONNECTED; ConnectSuccess(); }