private void UF_ChangeConnectState(NETCONNECT_STATE state, bool notifyState = true) { if (m_State != state) { Debugger.UF_Log(string.Format("NetConnect State Change: {0} -> {1}", m_State.ToString(), state.ToString())); m_State = state; //变更通知 if (notifyState && m_OnConnectState != null) { m_OnConnectState(m_Host, m_Port, (int)m_State); } } }
public NetConnection(string host, int port, ConnectType cType) { m_ReadBuffer = new CBytesBuffer(256); m_WriteBuffer = new CBytesBuffer(256); m_State = NETCONNECT_STATE.NONE; m_Host = host; m_Port = port; AddressFamily addressFamily = AddressFamily.InterNetwork; //转化IPV6地址 UF_ParseIPType(host, port, out host, out addressFamily); m_HostPort = string.Format("{0}:{1}", host, port); m_Socket = cType == ConnectType.TCP ? new TcpSocket(addressFamily) as ISocket : new UdpSocket(addressFamily) as ISocket; //心跳包协议号 m_ProtocalDataHeard = new ProtocalData(); m_ProtocalDataHeard.id = HeatProtocalID; }
//加入连接 //connectType == 0 Tcp //connectType == 1 Udp public bool UF_AddConnection(string host, int port, int timeout, ConnectType connectType) { lock (m_ListConnections) { NetConnection connection = null; for (int k = 0; k < m_ListConnections.Count; k++) { connection = m_ListConnections [k]; if (connection.host == host && connection.port == port) { NETCONNECT_STATE state = connection.connectState; if (state == NETCONNECT_STATE.CLOSED || state == NETCONNECT_STATE.NONE) { connection.Dispose(); return(false); } else if (state == NETCONNECT_STATE.WAITING) { Debugger.UF_Error(string.Format("Connection<{0}:{1}> is already waiting for connection!", host, port)); return(false); } else if (state == NETCONNECT_STATE.OPENED) { Debugger.UF_Error(string.Format("Connection<{0}:{1}> has already connected!", host, port)); return(false); } } } connection = new NetConnection(host, port, connectType); //设置状态回调函数 connection.onConnectStateChange = UF_OnConnectionStateChange; connection.timeOut = timeout; m_ListConnections.Add(connection); connection.UF_Connect(); } return(true); }