ok,服务器的结构已经构建完毕。尝试运行后发现,一个莫名的东西在那里不停的嘀嘀咕咕,你只知道了他在说话,你不知道他是谁。就跟QQ开启了匿名一样,有时候很好。但是,当某个键盘侠骂了你,你想提着“青龙偃月刀”去他家给他切个水果的时候,你发现不知道这个货是谁,你很生气。
所以,我们要添加一个分辨用户名字的东西。
这个东西可以分辨是什么人在发消息
首先,我们设计这样一个结构,用来把每个消息的类型存储
enum MessageType {
MT_BIND_NAME = 1,//客户名字
MT_CHAT_INFO = 2,//消息实体
MT_ROOM_INFO = 3,//聊天室分发
};
// 客户名
struct BindName {
char name[32];
int nameLen;
};
// 消息实体
struct ChatInformation {
char information[256];
int infoLen;
};
// 服务器分发消息
struct RoomInformation {
BindName name;
ChatInformation chat;
};
、***接收键盘输入时判断消息,然后通过类型却响应他**
bool parseMessage2(const std::string& input, int* type, std::string& outbuffer) {
auto pos = input.find_first_of(" ");
if (pos == std::string::npos)
return false;
if (pos == 0)
return false;
auto command = input.substr(0, pos);
if (command == "BindName") {
std::string name = input.substr(pos + 1);
if (name.size() > 32)
return false;
if (type)
*type = MT_BIND_NAME;
outbuffer = seriliaze(SBindName(std::move(name)));
return true;
} else if (command == "Chat") {
std::string chat = input.substr(pos + 1);
if (chat.size() > 256)
return false;
outbuffer = seriliaze(SChatInfo(std::move(chat)));;
if (type)
*type = MT_CHAT_INFO;
return true;
}
通过添加消息的类型,成功让键盘侠消失,大家在祥和的氛围中静默的聊天。世界美好!