C++项目 | 集群聊天服务器 | 客户端异常退出业务
1.clientCloseExecption
客户端异常退出处理函数要干两件事:
1.从map中删除用户的连接信息,因为要把底层的socket资源释放掉
2.更新用户状态信息 user表中状态改为offline
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
void ChatService::clientCloseExecption(const TcpConnectionPtr &conn) { User user; { lock_guard<mutex> lock(_connMutex); for(auto it=_userConnMap.begin();it!=_userConnMap.end();++it) { if(it->second==conn) { user.setId(it->first); _userConnMap.erase(it); break; } } } if(user.getId() != -1) { user.setState("offline"); _userModel.updateState(user); } }
|
2.onConnection
1 2 3 4 5 6 7 8 9 10 11 12
|
void ChatServer::onConnection(const TcpConnectionPtr& conn) { if(!conn->connected()) { ChatService::instance()->clientCloseExecption(conn); conn->shutdown(); } }
|
3.测试
启动Chatserver后
在另一个终端输入以下内容
1 2 3 4 5
| telnet 127.0.0.1 6000 {"msgid":1,"id":1,"password":"123456"} ctrl+] 回车 quit
|


在登录后,状态变为online
异常退出后状态变为offline

4.记录一下gdb使用
1 2 3 4
| gdb ChatServer break chatservice.cpp:135 # 源文件:断点行号 r #运行
|