-
Notifications
You must be signed in to change notification settings - Fork 0
/
RoomProtocolHandler.cpp
85 lines (81 loc) · 2.78 KB
/
RoomProtocolHandler.cpp
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include "RoomProtocolHandler.h"
RoomProtocolHandler::RoomProtocolHandler(RoomManager* roomManager) {
this->roomManager = roomManager;
}
std::string RoomProtocolHandler::handleProtocol(std::string protocol,User* user) {
std::vector<std::string> protocolParts = splitProtocol(protocol);
std::string command = protocolParts[0];
std::string response = "";
if (command == "createRoom") {
// 已有房间时退出
Room* room = user->getRoom();
if (room != nullptr) {
response = "Already Joined Room";
return response;
}
// 新建一个房间
std::string roomName = "";
if (protocolParts.size() > 1) {
roomName = protocolParts[1];
}
Room* newRoom = roomManager->createRoom(roomName);
response = "Room created with ID " + newRoom->getName();
roomManager->joinRoom(newRoom, user);
response += "\n"+roomManager->showRooms();
}
else if (command == "joinRoom") {
if (protocolParts.size() < 2) {
response = "Invalid protocol. Usage: joinRoom <room_id> ";
}
else {
string roomName = protocolParts[1];
Room* room = user->getRoom();
if (room != nullptr) {
response = "Already Joined Room";
}
else {
room=roomManager->getRoomByName("Room" + roomName);
if (room == nullptr)
{
response = "No room has name:" + roomName;
}
else
{
// 判断房间人数是否超限
if (room->getUsers().size() < 2)
{
roomManager->joinRoom(room, user);
response = "User " + user->getName() + " joined room " + room->getName();
}
else response = "room users full up: " + room->getName();
}
}
}
}
else if (command == "leaveRoom") {
if (user->getRoom() == nullptr) {
response = "Not In Any Room";
}
else {
roomManager->leaveRoom(user);
response = "User " + user->getName() + " left the room";
}
}
else if (command == "showRooms") {
response = roomManager->showRooms();
}
return response;
}
std::vector<std::string> RoomProtocolHandler::splitProtocol(std::string protocol) {
std::vector<std::string> parts;
std::string delimiter = " ";
size_t pos = 0;
std::string token;
while ((pos = protocol.find(delimiter)) != std::string::npos) {
token = protocol.substr(0, pos);
parts.push_back(token);
protocol.erase(0, pos + delimiter.length());
}
parts.push_back(protocol);
return parts;
}