CServer.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. #include "../pch/pch.h"
  2. #include "CServer.h"
  3. #include "../helper/CAliyunMNS.h"
  4. CServer::CServer()
  5. {
  6. }
  7. CServer::~CServer()
  8. {
  9. delete acceptor_;
  10. if (m_db != NULL)
  11. {
  12. sqlite3_close(m_db);
  13. }
  14. }
  15. void CServer::Init()
  16. {
  17. //初始化数据库
  18. InitSqlLite();
  19. //TCP服务器默认使用9001端口
  20. m_port = 9001;
  21. acceptor_ = new tcp::acceptor(io_context_, tcp::endpoint(tcp::v4(), m_port));
  22. //开始监听客户端的消息
  23. start_accept();
  24. //开始接受和处理mns的消息
  25. start_aliyun_mns();
  26. //任务队列,发送消息给客户端
  27. std::thread(&CServer::SendMessageToClient, this).detach();
  28. std::thread(&CServer::HandleOfflineMessage, this).detach();
  29. //开始异步执行
  30. io_context_.run();
  31. }
  32. void CServer::InitSqlLite()
  33. {
  34. wstring folderPath = CSystem::GetProgramDir() + L"\\db";
  35. if (!CSystem::IsDirExist(folderPath))
  36. {
  37. bool flag = CreateDirectory(folderPath.c_str(), NULL);
  38. bool a = flag;
  39. }
  40. //如果没有这个文件,这里会创建这个文件
  41. wstring path = CSystem::GetProgramDir() + L"\\db\\pos.db";
  42. string s_path = CLewaimaiString::UnicodeToUTF8(path);
  43. m_rc = sqlite3_open(s_path.c_str(), &m_db);
  44. if (m_rc)
  45. {
  46. LOG_INFO("Can't open database: " << sqlite3_errmsg(m_db));
  47. return;
  48. }
  49. else
  50. {
  51. LOG_INFO("Opened database successfully");
  52. }
  53. //初始化数据表
  54. std::string sql = "SELECT COUNT(*) FROM sqlite_master where type = 'table' and name = 'pos_message';";
  55. sqlite3_stmt * stmt = NULL;
  56. //读取厨房打印机的参数
  57. if (sqlite3_prepare_v2(m_db, sql.c_str(), -1, &stmt, NULL) == SQLITE_OK)
  58. {
  59. if (sqlite3_step(stmt) == SQLITE_ROW)
  60. {
  61. int count = sqlite3_column_int(stmt, 0);
  62. if (count == 0)
  63. {
  64. //说明没找到这个表,那么这个时候新建这个表,先释放前面的stmt
  65. sqlite3_finalize(stmt);
  66. stmt = NULL;
  67. sql = "CREATE TABLE pos_message(" \
  68. "id INTEGER PRIMARY KEY AUTOINCREMENT,"\
  69. "username CHAR(100) NOT NULL," \
  70. "due_time CHAR(100) NOT NULL," \
  71. "data CHAR(2000) NOT NULL);";
  72. if (sqlite3_prepare_v2(m_db, sql.c_str(), -1, &stmt, NULL) == SQLITE_OK)
  73. {
  74. //执行该语句
  75. if (sqlite3_step(stmt) != SQLITE_DONE)
  76. {
  77. std::string err = sqlite3_errmsg(m_db);
  78. LOG_INFO("create table fail: " << err.c_str());
  79. sqlite3_finalize(stmt);
  80. return;
  81. }
  82. //走到这里就是表创建成功了
  83. LOG_INFO("create table success");
  84. sqlite3_finalize(stmt);
  85. }
  86. else
  87. {
  88. LOG_INFO("create table prepare fail: " << sqlite3_errmsg(m_db));
  89. sqlite3_finalize(stmt);
  90. return;
  91. }
  92. }
  93. else
  94. {
  95. //说明已经有这个表了,就不用再创建了
  96. sqlite3_finalize(stmt);
  97. }
  98. }
  99. }
  100. }
  101. bool CServer::AddMessageToDB(std::string username, std::string due_time, std::string data)
  102. {
  103. int result = sqlite3_exec(m_db, "BEGIN;", 0, 0, 0);
  104. std::string sql = "INSERT INTO pos_message (username, due_time, data) VALUES ('" + username + "' ,'" + due_time + "','" + data + "')";
  105. result = sqlite3_exec(m_db, sql.c_str(), 0, 0, 0);
  106. result = sqlite3_exec(m_db, "COMMIT;", 0, 0, 0);
  107. if (result == SQLITE_OK)
  108. {
  109. LOG_INFO("save params success");
  110. return true;
  111. }
  112. LOG_INFO("save params fail");
  113. return false;
  114. }
  115. /*
  116. *把要处理离线消息的用户名,加入到队列
  117. **/
  118. void CServer::CheckOfflineMessage(std::string username)
  119. {
  120. m_offlineMsg_mutex.lock();
  121. m_offlineMsg.push(username);
  122. m_offlineMsg_mutex.unlock();
  123. }
  124. void CServer::HandleOfflineMessage()
  125. {
  126. while (1)
  127. {
  128. m_offlineMsg_mutex.lock();
  129. if (m_offlineMsg.empty())
  130. {
  131. m_offlineMsg_mutex.unlock();
  132. CSystem::my_sleep(1);
  133. continue;
  134. }
  135. std::string username = m_offlineMsg.front();
  136. m_offlineMsg.pop();
  137. m_offlineMsg_mutex.unlock();
  138. //先把过期的消息全部删除
  139. std::string curTime = CLewaimaiTime::DatetimeToString(time(NULL));
  140. std::string sql = "DELETE FROM pos_message WHERE username = '" + username + "' AND due_time <= '" + curTime + "';";
  141. sqlite3_exec(m_db, sql.c_str(), 0, 0, 0);
  142. //再看有没有剩余的离线消息
  143. sql = "SELECT * FROM pos_message WHERE username = '" + username + "' AND due_time > '" + curTime + "';";
  144. sqlite3_stmt * stmt = NULL;
  145. if (sqlite3_prepare_v2(m_db, sql.c_str(), -1, &stmt, NULL) == SQLITE_OK)
  146. {
  147. while (sqlite3_step(stmt) == SQLITE_ROW)
  148. {
  149. std::string username = (char*)sqlite3_column_text(stmt, 1);
  150. std::string due_time = (char*)sqlite3_column_text(stmt, 2);
  151. std::string data = (char*)sqlite3_column_text(stmt, 3);
  152. m_map_mutex.lock();
  153. if (m_clients_map.find(username) == m_clients_map.end())
  154. {
  155. m_map_mutex.unlock();
  156. //socket失效了,下次再处理
  157. break;
  158. }
  159. else
  160. {
  161. CClientSession* session = m_clients_map[username];
  162. m_map_mutex.unlock();
  163. session->send_message(data);
  164. }
  165. }
  166. sqlite3_finalize(stmt);
  167. }
  168. else
  169. {
  170. //异常情况
  171. sqlite3_finalize(stmt);
  172. }
  173. //把所有数据库的离线消息都删掉
  174. //sql = "DELETE FROM pos_message WHERE username = '" + username + "';";
  175. //sqlite3_exec(m_db, sql.c_str(), 0, 0, 0);
  176. }
  177. }
  178. void CServer::start_accept()
  179. {
  180. //新建一个客户端会话
  181. CClientSession* new_session = new CClientSession(io_context_);
  182. new_session->SetServer(this);
  183. //记录客户端的顺序
  184. m_nClientCount++;
  185. new_session->SetNum(m_nClientCount);
  186. acceptor_->async_accept(new_session->socket(),
  187. boost::bind(&CServer::handle_accept, this, new_session,
  188. boost::asio::placeholders::error));
  189. }
  190. void CServer::handle_accept(CClientSession* new_session,
  191. const boost::system::error_code& error)
  192. {
  193. if (!error)
  194. {
  195. new_session->start();
  196. }
  197. else
  198. {
  199. delete new_session;
  200. }
  201. //继续监听下一个客户端
  202. start_accept();
  203. }
  204. /*
  205. *将客户端的用户名和socket进行绑定,每个用户名只能绑定一个socket,后登陆的会删掉前面先登录的
  206. **/
  207. void CServer::BindUsername(std::string username, CClientSession* session)
  208. {
  209. m_map_mutex.lock();
  210. if (m_clients_map.find(username) != m_clients_map.end() && m_clients_map[username]->GetNum() < session->GetNum())
  211. {
  212. //之前已经存在了一个,先把直接的关闭掉
  213. m_clients_map[username]->stop();
  214. }
  215. m_clients_map[username] = session;
  216. m_map_mutex.unlock();
  217. }
  218. void CServer::DeleteClient(std::string username)
  219. {
  220. m_map_mutex.lock();
  221. if (m_clients_map.find(username) != m_clients_map.end())
  222. {
  223. m_clients_map.erase(username);
  224. }
  225. m_map_mutex.unlock();
  226. }
  227. void CServer::start_aliyun_mns()
  228. {
  229. //开启线程,监听消息
  230. int n_cpu = CSystem::get_CPU_core_num();
  231. LOG_INFO("cpu num:" << n_cpu);
  232. //创建跟CPU核数2倍的线程数量来处理消息队列的消息
  233. for(int i = 0; i < n_cpu * 2; i++)
  234. {
  235. std::thread t(&CServer::ReceiveMNSMessage, this);
  236. t.detach();
  237. }
  238. }
  239. /*
  240. *接收消息,并且对消息进行处理
  241. **/
  242. void CServer::ReceiveMNSMessage()
  243. {
  244. CAliyunMNS mns(CConfigReader::getTaskQueue());
  245. if(mns.getIsInit() == false)
  246. {
  247. //初始化消息队列失败了,线程直接退出
  248. LOG_INFO("Init AliyunMNS Failed!");
  249. return;
  250. }
  251. while(true)
  252. {
  253. std::string message = mns.getMessage();
  254. if(message == "error!")
  255. {
  256. continue;
  257. }
  258. LOG_INFO("get new message:" << message.c_str());
  259. //获取到了新的消息,开始进行处理
  260. rapidjson::Document document;
  261. document.Parse(message.c_str());
  262. if(!document.IsObject())
  263. {
  264. LOG_INFO("message 非法!");
  265. continue;
  266. }
  267. //处理消息类型
  268. std::string username = document["username"].GetString();
  269. std::string timestamp = document["timestamp"].GetString();
  270. std::string use_time = document["use_time"].GetString();
  271. rapidjson::Value& data = document["data"];
  272. rapidjson::StringBuffer sbBuf;
  273. rapidjson::Writer<rapidjson::StringBuffer> Writer(sbBuf);
  274. data.Accept(Writer);
  275. std::string strData = std::string(sbBuf.GetString());
  276. //判断是否过期
  277. if (time(NULL) > atoi(timestamp.c_str()) + atoi(use_time.c_str()))
  278. {
  279. //消息过了有效期,直接丢弃
  280. continue;
  281. }
  282. //把消息放进队列
  283. CClientMessage newMessage;
  284. newMessage.m_username = username;
  285. time_t start = atoi(timestamp.c_str());
  286. time_t due = atoi(use_time.c_str());
  287. time_t end = start + due;
  288. newMessage.m_due_time = CLewaimaiTime::DatetimeToString(end);
  289. newMessage.m_data = strData;
  290. m_queue_mutex.lock();
  291. m_message_queue.push(newMessage);
  292. m_queue_mutex.unlock();
  293. }
  294. }
  295. /*
  296. *负责把队列中的消息发给客户端
  297. **/
  298. void CServer::SendMessageToClient()
  299. {
  300. while (1)
  301. {
  302. m_queue_mutex.lock();
  303. if (m_message_queue.empty())
  304. {
  305. m_queue_mutex.unlock();
  306. CSystem::my_sleep(1);
  307. continue;
  308. }
  309. CClientMessage msg = m_message_queue.front();
  310. m_message_queue.pop();
  311. m_queue_mutex.unlock();
  312. std::string username = msg.m_username;
  313. std::string due_time = msg.m_due_time;
  314. std::string data = msg.m_data;
  315. //判断消息对应的用户是否在线,如果不在线就消息暂存在数据库
  316. m_map_mutex.lock();
  317. if (m_clients_map.find(username) == m_clients_map.end())
  318. {
  319. m_map_mutex.unlock();
  320. //客户端不在线,操作存数据库
  321. AddMessageToDB(username, due_time, data);
  322. }
  323. else
  324. {
  325. CClientSession* session = m_clients_map[username];
  326. m_map_mutex.unlock();
  327. //直接把消息发给客户端
  328. session->send_message(data);
  329. }
  330. }
  331. }