online类
成员变量
1.成员变量哈希表1
writeFdToReadFd
2.成员变量哈希表2
accountToFd
3.成员变量哈希表,保存已经登录的用户
userMap
成员函数
//
// Created by cswen on 2020/8/3.
//
#pragma once
#include<json/json.h>
#include<string>
#include"../Util/MyTime.h"
#include<unordered_map>
#include <utility>
using namespace std;
class Online
{
private:
struct user
{
int account; //账户
string username;//用户名
string loginTime;//登陆时间
};
unordered_map<int, int> writeFdToReadFd;//键:发送文件描述符,值 文件描述符。 发送文件描述符-接收文件描述符,哈希表。
unordered_map<int, int> accountToFd; //键:账户,值 文件描述符。 账户-文件描述符,哈希表。
unordered_map<int, user> userMap; //键:账号 值:用户结构体。 账号-用户,哈希表。
public:
string getOnlineListStr();//获取在线列表
bool appendUser(int account, string username);//添加用户accountToFd,添加一个用户。
bool removeUser(int account);//删除用户
bool appendUser(pair<int, string> &user);//向成员变量
int getReadFd(int writeFd);
vector<int> getAllReadFd();
bool appendWriteFd(int account, int fd);//向
bool appendReadFd(int account, int fd);
string getUserJsonStr(int account);
string getUserName(int account); //得到用户名
bool isLogin(int account);
};
//
// Created by cswen on 2020/8/3.
//
#include "Online.h"
//得到在线列表字符串。
string Online::getOnlineListStr()
{
Json::Value onlineList; //实例化一个json value 对象
for (auto &item : userMap) //遍历账号-用户哈希表
{
Json::Value userJson;//在栈空间实例化一个json value 对象。
userJson["account"] = item.second.account;
userJson["username"] = item.second.username;
userJson["loginTime"] = item.second.loginTime;
onlineList.append(userJson); //json api 函数
}
return onlineList.toStyledString();//json api 。
}
//向在线列表添加用户
bool Online::appendUser(int account, string username)
{
user u = {account, move(username), MyTime::getCurrentFormatTimeStr()};//创建一个user结构体成员变量并进行赋值
userMap[account] = u;//将结构体成员变量存进哈希表。
return true;
}
//从在线列表中移除用户
bool Online::removeUser(int account)
{
userMap.erase(account);//从哈希表中,删除,账号-用户那一栏
writeFdToReadFd.erase(accountToFd[account]);//发送文件描述-接收文件描述符,哈希表。删除文件描述那一栏。
accountToFd.erase(account);//账户-文件描述符哈希表,删除账号所在一栏。 账户,发送文件描述符,接收文件描述符,三者具有映射关系。
return true;
}
//向在线列表添加用户
bool Online::appendUser(pair<int, string> &user)
{
return appendUser(user.first, user.second);
}
int Online::getReadFd(int writeFd)
{
return writeFdToReadFd[writeFd];
}
//返回保存所有在线的读文件描述符的vector容器
vector<int> Online::getAllReadFd()
{
vector<int> v;
for (auto &item : writeFdToReadFd)
{
v.push_back(item.second);
}
return v;
}
//在线列表添加写文件描述符
bool Online::appendWriteFd(int account, int fd)
{
accountToFd[account] = fd;
return true;
}
//添加接收文件描述符。
bool Online::appendReadFd(int account, int fd)
{
writeFdToReadFd[accountToFd[account]] = fd;
return true;
}
string Online::getUserJsonStr(int account)
{
Json::Value jsonUser;
jsonUser["account"] = account;
jsonUser["username"] = userMap[account].username;
return jsonUser.toStyledString();
}
//根据账户获取用户名
string Online::getUserName(int account)
{
return userMap[account].username;
}
//检验是否登陆
bool Online::isLogin(int account)
{
return userMap.count(account) != 0;
}