//连接 public void Connect(string ip, int port, int type, LuaFunction callback) { if (true == isConnected) { //Debug.LogError("已经连接上了"); return; } m_IP = ip; m_Port = port; //不是同一个callback,释放掉 if (callback != m_LuaConnectCallback || false == callback.Equals(m_LuaConnectCallback)) { if (m_LuaConnectCallback != null) { m_LuaConnectCallback.Dispose(); } m_LuaConnectCallback = callback; m_ConnectAction = delegate(int errorCode, int reason) { m_LuaConnectCallback.Action <int, int>(errorCode, reason); }; } Debug.Log(" udp==0,tcp==1 当前尝试连接的类型 :" + type + "连接IP" + m_IP + "连接的端口:" + m_Port); if (0 == m_Port) { m_ConnErrorCode = ConnectErrorCode.Lost; return; } //放入待回收的池子 if (null != m_CurrentSocketClient) { m_CurrentSocketClient.Disconnect(); m_SocketList.Add(m_CurrentSocketClient); m_CurrentSocketClient = null; } switch ((CONNECT_TYPE)type) { case CONNECT_TYPE.Connect_Type_UDP: m_CurrentSocketClient = new UDPSocketClient(); break; case CONNECT_TYPE.Connect_Type_TCP: default: m_CurrentSocketClient = new TCPSocketClient(); break; } m_eReason = SOCKET_ERROR.SOCKET_ERROR_NON; ++m_nCurSocketID; m_CurrentSocketClient.SetSink(this); m_CurrentSocketClient.SetSocketID(m_nCurSocketID); //连接服务器 ReConnect(m_IP, m_Port); }
//连接失败 public void OnConnectError(uint nSocketID, SOCKET_ERROR eReason) { if (null == m_CurrentSocketClient || m_nCurSocketID != nSocketID) { return; } // Debug.Log("Connect error!"); m_ConnErrorCode = ConnectErrorCode.Error; m_eReason = eReason; }
//关闭 public void OnClose(uint nSocketID) { if (null == m_CurrentSocketClient || m_nCurSocketID != nSocketID) { return; } // Debug.Log("Connection is close!"); m_eReason = SOCKET_ERROR.SOCKET_ERROR_CONNECT_CLOSE; m_ConnErrorCode = ConnectErrorCode.Lost; }
//检查连接错误 public void CheckConnectError() { if (m_ConnErrorCode != ConnectErrorCode.Unknow && m_ConnectAction != null) { isConnected = (ConnectErrorCode.Success == m_ConnErrorCode); ConnectErrorCode lastError = m_ConnErrorCode; SOCKET_ERROR eReason = m_eReason; m_ConnErrorCode = ConnectErrorCode.Unknow; m_ConnectAction((int)lastError, (int)eReason); } }