public void connectTo(string ip, int port, object userData) { if (valid()) { throw new InvalidOperationException("Have already connected!"); } string newip = ip; #if UNITY_IOS newip = NtUniSdk.Unity3d.SdkU3d.getIpStr(ip); IPAddress[] addrIps = Dns.GetHostAddresses(newip); AddressFamily ipTypes = addrIps[0].AddressFamily; m_socket = new Socket(ipTypes, SocketType.Stream, ProtocolType.Tcp); LoggerHelper.Warning("IpTypes = {0}", ipTypes); #else m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); #endif m_socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, MAX_BUFFER_SIZE); m_socket.NoDelay = true; ConnectState state = new ConnectState(); this.ip = newip; this.port = port; state.connectIP = newip; state.connectPort = port; state.userData = userData; state.socket = m_socket; state.networkInterface = this; UnityEngine.Debug.Log("connect to " + newip + ":" + port); try { m_socket.BeginConnect(new IPEndPoint(IPAddress.Parse(newip), port), new AsyncCallback(connectCB), state); connectCallbackFlag = false; LNetwork.GetInstance().StartCoroutine(waitForConnect(state)); this.Connecting = true; } catch (SocketException e) { UnityEngine.Debug.LogFormat("connectTo error: {0}", e.ToString()); state.errorType = SocketErrorType.SocketException; state.error = e.ToString(); state.success = false; _onConnectStatus(state); } catch (Exception e) { UnityEngine.Debug.LogFormat("connectTo error: {0}", e.ToString()); state.errorType = SocketErrorType.Exception; state.error = e.ToString(); state.success = false; _onConnectStatus(state); } }
private static void _onConnectStatus(ConnectState state) { NetworkInterface networkInterface = state.networkInterface; networkInterface.Connecting = false; if (state.success) { // 创建发送和接收进程开始接收数据 networkInterface.startTcpWorker(); // 启动协程判断网络是否断开 LNetwork.GetInstance().StartCoroutine(CheckNetworkStateLoop(networkInterface)); } else { networkInterface.Close(); UnityEngine.Debug.Log("connect error: " + state.error); } if (NetworkInterface.OnConn != null) { NetworkInterface.OnConn.Invoke(state.success); } //EventDispatcher.Instance.TriggerEvent<bool, NetworkInterface.ConnectState>(EventIdType.ConnectSuccess, state.success, state); }