// 连接远程地址 public INetSession Connect(string remoteAddr, Int32 remotePort, bool isSync, ref bool isSuccess) { isSuccess = false; if (remoteAddr == null || remotePort <= 0) { Trace.Assert(false, "Connect param error"); return(null); } NetSessionImpl netSession = NetSessionPool.GetInstance().MallocNetSession(); if (netSession == null) { Trace.Assert(false, "malloc session null"); return(null); } // 同步连接 if (isSync) { if (!netSession.PostConnect(remoteAddr, remotePort, true)) { NetSessionPool.GetInstance().FreeNetSession(netSession); return(null); } // 设置会话的状态 NetSessionState sessionState = new NetSessionState(); sessionState.Reset((Int32)NETSESSIONSTATE.netSessionStateUsing); netSession.SetSessionState(ref sessionState); // 投递接收操作 if (!netSession.PostRcv()) { // 关闭会话,返回会话池 NetSessionPool.GetInstance().FreeNetSession(netSession); return(null); } // 添加到活动会话队列 netSessionDic.Add(netSession.GetSessionID(), netSession); isSuccess = true; return((INetSession)netSession); } // 异步连接 else { if (netSession.PostConnect(remoteAddr, remotePort, false)) { isSuccess = true; } } return(null); }
// 处理添加、删除网络会话事件 #region public void HandleAddOrDelEvent(AddOrDelSessionEvent addOrDelEvent) { NetSessionImpl netSession = addOrDelEvent.netSession; if (netSession == null) { return; } switch (addOrDelEvent.eventType) { case ADDORDELSESSIONEVENT.addNetSession: { // 设置会话的状态 NetSessionState sessionState = new NetSessionState(); sessionState.Reset((Int32)NETSESSIONSTATE.netSessionStateUsing); netSession.SetSessionState(ref sessionState); if (!netSession.PostRcv()) { // 关闭会话,返回会话池 NetSessionPool.GetInstance().FreeNetSession(netSession); } else { netSessionDic.Add(netSession.GetSessionID(), netSession); // 通知上层 if (netSessionConnectedCallbackFunc != null) { netSessionConnectedCallbackFunc((INetSession)netSession, addOrDelEvent.eventPlace, true); } } } break; case ADDORDELSESSIONEVENT.delNetSession: { // 通知应用层 if (addOrDelEvent.eventPlace != EVENTSESSIONPLACE.appDelSession) { if (netSessionClosedCallbackFunc != null) { netSessionClosedCallbackFunc(addOrDelEvent.netSession, addOrDelEvent.eventPlace); } NetSessionState sessionState = new NetSessionState(); sessionState.Reset((Int32)NETSESSIONSTATE.netSessionStateMax); sessionState.appUseState = (Int32)NETSESSIONSTATE.netSessionStateShutdown; addOrDelEvent.netSession.SetSessionState(ref sessionState); } } break; case ADDORDELSESSIONEVENT.asyncConnectFailed: { // 通知上层 if (netSessionConnectedCallbackFunc != null) { netSessionConnectedCallbackFunc((INetSession)netSession, addOrDelEvent.eventPlace, false); } // 关闭会话,返回会话池 NetSessionPool.GetInstance().FreeNetSession(netSession); } break; default: break; } }