假设有2个用户,用户1把它的id号和要说的内容发过去,服务器要主动地去给用户2推送这个消息,但是用户2又不知道什么时候谁会给他说话,他不可能去服务器上拉取消息,所以这个聊天 肯定得是服务器推送给用户2,所以聊天服务器也必须是长连接,不仅仅是客户端请求,服务端被动接收,而且服务端还要主动推送消息到客户端,所以我们拿到用户2的id号,怎么知道这个用户的连接connection在哪里,所以,我们在业务层要想办法,一个用户一个connection,登录成功,连接就建立成功了,这个连接就可以存储下来。
记录用户的连接信息和线程安全问题
我们完善chatservice.hpp
增加
#include <mutex>
//存储在线用户的通信连接,用户的id, TcpConnectionPtr
unordered_map<int, TcpConnectionPtr> _userConnMap;
//定义互斥锁,保证_userConnMap的线程安全
mutex _connMutex;
完整文件代码
#ifndef CHATSERVICE_H
#define CHATSERVICE_H
#include <muduo/net/TcpConnection.h>
#include <unordered_map>//一个消息ID映射一个事件处理
#include <functional>
#include <mutex>
using namespace std;
using namespace muduo;
using namespace muduo::net;
#include "usermodel.hpp"
#include "json.hpp"
using json = nlohmann::json;
//表示处理消息的事件回调方法类型,事件处理器,派发3个东西
using MsgHandler = std::function<void(const TcpConnectionPtr &conn, json &js, Timestamp)>;
//聊天服务器业务类
class ChatService
{
public:
//获取单例对象的接口函数
static ChatService *instance();
//处理登录业务
void login(const TcpConnectionPtr &conn, json &js, Timestamp time);
//处理注册业务
void reg(const TcpConnectionPtr &conn, json &js, Timestamp time);
//获取消息对应的处理器
MsgHandler getHandler(int msgid);
private:
ChatService();//单例
//存储消息id和其对应的业务处理方法,消息处理器的一个表,写消息id对应的处理操作
unordered_map<int, MsgHandler> _msgHandlerMap;
//存储在线用户的通信连接,用户的id, TcpConnectionPtr
unordered_map<int, TcpConnectionPtr> _userConnMap;
//定义互斥锁,保证_userConnMap的线程安全
mutex _connMutex;
//数据操作类对象
UserModel _userModel;
};
然后我们完善chatservice.cpp
在登录业务函数的成功后的操作添加
//登录成功,记录用户连接信息
{
lock_guard<mutex> lock(_connMutex);
_userConnMap.insert({id, conn});
}//加个作用域,出了这个右括号就自动解锁
完整文件代码
#include "chatservice.hpp"
#include "public.hpp"
#include <muduo/base/Logging.h>//muduo的日志
using namespace std;
using namespace muduo;
//获取单例对象的接口函数
ChatService *ChatService::instance()
{
static ChatService service;
return &service;
}
//构造方法,注册消息以及对应的Handler回调操作
ChatService::ChatService()
{
//用户基本业务管理相关事件处理回调注册
_msgHandlerMap.insert({LOGIN_MSG, std::bind(&ChatService::login, this, _1, _2, _3)});
_msgHandlerMap.insert({REG_MSG, std::bind(&ChatService::reg, this, _1, _2, _3)});
}
//获取消息对应的处理器
MsgHandler ChatService::getHandler(int msgid)
{
//记录错误日志,msgid没有对应的事件处理回调
auto it = _msgHandlerMap.find(msgid);
if (it == _msgHandlerMap.end())//找不到
{
//返回一个默认的处理器,空操作,=按值获取
return [=](const TcpConnectionPtr &conn, json &js, Timestamp) {
LOG_ERROR << "msgid:" << msgid << " can not find handler!";//muduo日志会自动输出endl
};
}
else//成功的话
{
return _msgHandlerMap[msgid];//返回这个处理器
}
}
//处理登录业务 id pwd 检测pwd
void ChatService::login(const TcpConnectionPtr &conn, json &js, Timestamp time)
{
int id = js["id"].get<int>();//获取id号
string pwd = js["password"];//获取密码
User user = _userModel.query(id);//查找
if (user.getId() == id && user.getPwd() == pwd)//查出来了,登录成功
{
if (user.getState() == "online")
//该用户已经登录,不允许重复登录
{
json response;
response["msgid"] = LOGIN_MSG_ACK;
response["errno"] = 2;
response["errmsg"] = "this account is using, input another!";
conn->send(response.dump());
}
else
{
//登录成功,记录用户连接信息,要考虑线程安全,因为多线程访问
{
lock_guard<mutex> lock(_connMutex);
_userConnMap.insert({id, conn});
}//加个作用域,出了这个右括号就自动解锁
//登录成功,更新用户状态信息 state offline=>online
user.setState("online");
_userModel.updateState(user);
json response;
response["msgid"] = LOGIN_MSG_ACK;
response["errno"] = 0;
response["id"] = user.getId();
response["name"] = user.getName();
conn->send(response.dump());
}
}
else
{
//该用户不存在,用户存在但是密码错误,登录失败
json response;
response["msgid"] = LOGIN_MSG_ACK;
response["errno"] = 1;
response["errmsg"] = "id or password is invalid!";
conn->send(response.dump());
}
}
//处理注册业务 name password
void ChatService::reg(const TcpConnectionPtr &conn, json &js, Timestamp time)
{
string name = js["name"];//获取名字
string pwd = js["password"];//获取密码
User user;//创建用户对象
user.setName(name);
user.setPwd(pwd);
bool state = _userModel.insert(user);//新用户的插入
if (state)//插入成功
{
//注册成功
json response;
response["msgid"] = REG_MSG_ACK;
response["errno"] = 0;
response["id"] = user.getId();
conn->send(response.dump());//回调 ,返回json字符串
}
else//插入失败
{
//注册失败
json response;
response["msgid"] = REG_MSG_ACK;
response["errno"] = 1;
conn->send(response.dump());//回调 ,返回json字符串
}
}
编译成功