CServer.cpp 11 KB

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