void my::GateServer::handle_connect(ConnectionPtr conn, boost::system::error_code err) { if (err) { LogW << "server name: " << conn->getNetId() << " connect error: " << err.message() << LogEnd; if (conn->getSocket().is_open()) { LogW << "Close Socket!!" << LogEnd; conn->getSocket().close(); } return; } else { //输出一下这个是成功连接了哪个服务器 LogD << "server name: " << conn->getNetId() << " connect success!" << LogEnd; try { static ip::tcp::no_delay option(true); conn->getSocket().set_option(option); //start conn->start(); }catch(std::exception& e) { LogE << "Connect to server EXCEPTION!!! server=" << conn->getNetId() << " reason=" << e.what() << LogEnd; } } }
void my::GateServer::onPlayerLogin(int playerId, int netId) { if (netId < 0 || playerId < 0) { return; } ConnectionMap::iterator it = m_PlayerMap.find(playerId); if (it != m_PlayerMap.end()) { ConnectionPtr conn = it->second; if (conn->getNetId() == netId) { //玩家已在线,无需再登陆 return; } //kickConnection(conn); } it = m_ConnMap.find(netId); if (it == m_ConnMap.end()) { //找不到conn,哪里有问题? LogW << " Can't find connection, netId=" << netId << LogEnd; } else { ConnectionPtr conn = it->second; conn->setPlayerId(playerId); conn->setHeartBeat(m_SystemTime); //登陆的时候心跳一次 m_PlayerMap.insert(ConnectionMap::value_type(playerId, conn)); LogD << " New User Login, playerId=" << playerId << " netId=" << netId << LogEnd; } }
bool my::GateServer::kickConnection(ConnectionPtr conn) { int netId = conn->getNetId(); if (netId < 0) { //server, don't do anything stupid } else { boost::recursive_mutex::scoped_lock lock(mtx); ConnectionMap::iterator it = m_ConnMap.find(netId); if (it != m_ConnMap.end()) { ConnectionPtr tmpConn = it->second; m_ConnMap.erase(it);//应检查conn和tmpConn是否相同 m_nConnCount--; int playerId = conn->getPlayerId(); kickPlayer(playerId, netId); tmpConn->stop(); LogD << "erase from connMap" << LogEnd; return true; } } return false; }
void my::GateServer::checkHeartBeat(boost::system_time tmp) { ConnectionMap::iterator it = m_ConnMap.begin(); for (; it != m_ConnMap.end(); ) { ConnectionPtr conn = it->second; ++it; if ((tmp - conn->getHeartBeat()).total_seconds() > 180)//一分钟没心跳,死了吧 { LogW << "Connection is dead, kick it! netId=" << conn->getNetId() << " playerId=" << conn->getPlayerId() << LogEnd; kickConnection(conn); //todo kick } } }
void my::GameHandler::onRecv(ConnectionPtr conn, NetMessage& req) { int netId = conn->getNetId(); //©иртеп╤оnetId int protoId = req.getProto(); int playerId = req.getPlayerId(); if (protoId > my::protocol::GAME_BEGIN && protoId < my::protocol::GAME_END) { gameSvr.pushMessage(req); //NetMessage rsp; //funcHandlerMgr.runFuncHandler(req, rsp); //rsp.serialize(); //conn->sendMessage(rsp); } else { LogW << "Unknown Protocol, protoId=" << protoId << " playerId=" << playerId << LogEnd; } }