Bool HawkGateThread::CloseSession(SID iSid) { if (iSid) { SessionMap::iterator it = m_mSession.find(iSid); if (it != m_mSession.end()) { //剔除会话列表 Session* pSession = it->second; m_mSession.erase(it); //添加日志 HawkFmtLog("SessionClose, SID: %u, Address: %s", pSession->Sid, pSession->Addr->ToString().c_str()); //释放会话 FreeSession(pSession); //调用性能监视器 if (m_pGateway->GetProfiler()) m_pGateway->GetProfiler()->RegConnect(false); //修改连接数 m_pGateway->RegConnection(false); return true; } } return false; }
Bool HawkGateThread::StartSession(SOCKET hSocket, const SocketAddr& sAddr) { //套接字有效 if (hSocket == INVALID_SOCKET) return false; //创建缓存事件 bufferevent* pEvent = bufferevent_socket_new((event_base*)m_pBase, hSocket, BEV_OPT_CLOSE_ON_FREE); if (!pEvent) return false; //创建会话 Session* pSession = AllocSession(hSocket, sAddr); if (!pSession) { bufferevent_free(pEvent); return false; } pSession->Event = pEvent; //设置回调 bufferevent_setcb(pEvent, hawk_GateSessionRead, hawk_GateSessionWrite, hawk_GateSessionError, pSession); //设置读超时, 可做为心跳机制 Int32 iTimeout = m_pGateway->GetSessionTimeout(); if (iTimeout > 0) { struct timeval tv; tv.tv_sec = iTimeout / 1000; tv.tv_usec = (iTimeout % 1000) * 1000; bufferevent_set_timeouts(pEvent, &tv, NULL); } //开启读写事件 bufferevent_enable(pEvent, EV_READ | EV_WRITE); //添加到会话列表 m_mSession[pSession->Sid] = pSession; //调用性能监视器 if (m_pGateway->GetProfiler()) m_pGateway->GetProfiler()->RegConnect(true); //添加日志 HawkFmtLog("SessionStart, Sid: %u, Address: %s", pSession->Sid, pSession->Addr->ToString().c_str()); return true; }
Bool HawkSession::Init(const SocketAddr& sAddr, Int32 iTimeout) { //先关闭 Close(); //连接指定地址 if (!m_sSocket.IsValid() && !m_sSocket.InitTcpClient(sAddr, true, iTimeout)) { #ifdef _DEBUG HawkFmtLog("InitTcpClient Failed, Addr: %s", sAddr.ToString().c_str()); #endif return false; } m_sAddress = sAddr; return true; }