CWebsocketServer.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. #if (defined _WIN32 || defined _WIN64)
  2. #include "stdafx.h"
  3. #include "../mod_browser/IEBrowser_client_g.h"
  4. #endif
  5. #include "CWebsocketServer.h"
  6. #include "baseEx.h"
  7. #include "CModTools.h"
  8. #include <vector>
  9. #include "MessageType.h"
  10. #include <future>
  11. #include <boost/thread/thread.hpp>
  12. #include <boost/thread/lock_guard.hpp>
  13. #include <iostream>
  14. #include <thread>
  15. #include "guitask/guitask.h"
  16. #define DEFAULT_SERVER_PORT 9002
  17. namespace Chromium{
  18. CWebsocketServer::CWebsocketServer(const char* strPath, CEntityBase* pEntity):
  19. m_wsserver(), m_ios(),m_serializer(NULL),m_socket(NULL),m_pEntity(pEntity),m_initSuccess(false)
  20. {
  21. DbgEx("CWebsocketServer constructor");
  22. // Initialize socket client
  23. DbgEx("Initialize socket client");
  24. this->m_pEntity = pEntity;
  25. m_socket = new CSocketClient(m_ios, "127.0.0.1", "4504", pEntity, 0);
  26. DbgEx("Set socket client MessageHandler -- message_handler");
  27. m_socket->SetMessageHandler(this);
  28. // Initialize serializer
  29. DbgEx("Initialize serializer");
  30. this->m_serializer = CWSCodec::getInstance();
  31. this->m_serializer->setEntityHandler(pEntity->GetFunction());
  32. this->m_serializer->init(strPath);
  33. while (Error_Succeed != m_socket->Connect())
  34. Sleep(100);
  35. DbgEx("init Entity Session Manager");
  36. myTest();
  37. m_esm = new EntitySessionManager();
  38. init_websocket();
  39. init_entity_sessions();
  40. }
  41. void CWebsocketServer::updateMsgPool(std::string entityName, std::string &payload, websocketpp::connection_hdl hdl)
  42. {
  43. //存储的消息应具备时效性,保证一个hdl只有一个记录的消息
  44. auto it = m_msg_pool.find(entityName);
  45. if (it != m_msg_pool.end())
  46. {
  47. auto &curArr = it->second;
  48. for (auto i = curArr.begin(); i != curArr.end(); i++)
  49. {
  50. if (&hdl == &i->first)
  51. {
  52. curArr.erase(i);
  53. break;
  54. }
  55. }
  56. it->second.push_back(std::make_pair(hdl, payload));
  57. }
  58. else
  59. {
  60. std::vector<std::pair<websocketpp::connection_hdl, std::string>> t_saveMsgs;
  61. t_saveMsgs.push_back(std::make_pair(hdl, payload));
  62. m_msg_pool.insert(std::make_pair(entityName, t_saveMsgs));
  63. }
  64. }
  65. void CWebsocketServer::storeEntityWithCLass(std::string entityName, std::string entityClass)
  66. {
  67. if (m_entityAndClass.end() == m_entityAndClass.find(entityName))
  68. m_entityAndClass.insert(std::make_pair(entityName, entityClass)); //not exist
  69. }
  70. std::pair<bool, std::string> CWebsocketServer::getEntityClass(std::string entityName)
  71. {
  72. auto it = m_entityAndClass.find(entityName);
  73. if (m_entityAndClass.end() == it)
  74. return std::make_pair(false, "");
  75. else
  76. return std::make_pair(true, it->second);
  77. }
  78. void CWebsocketServer::do_sendJsonStartSession(std::string entityName, std::string entityClass)
  79. {
  80. auto startSessionReq = m_esm->GetStartSessionRequest(entityName, entityClass);
  81. auto sessionBuf = this->m_serializer->JsonToBuffer(startSessionReq.second).second;
  82. if (nullptr == sessionBuf)
  83. {
  84. DbgEx("JsonToBuffer return NULL !");
  85. return;
  86. }
  87. m_esm->StoreSessionReq(startSessionReq.first, entityName);
  88. m_esm->MakeNewTransID(sessionBuf, 0);
  89. //保存msg,先建立session
  90. if (m_esm->checkBeginSession(entityName)) {
  91. m_esm->updateBeginSessionTime(entityName);
  92. WriteToFramework(sessionBuf);
  93. }
  94. else
  95. DbgEx("Already begin session in 5s, %s", entityName.c_str());
  96. }
  97. void CWebsocketServer::WriteToFramework(CMessage* msg)
  98. {
  99. m_socket->Write(msg);
  100. if (chromiumRpcTask::get_mutable_instance().isChromiumRpcWork()) chromiumRpcTask::get_mutable_instance().publishMsg({ generateTimeStr(), "WriteToFramework---------" + msg->printfHEX() });
  101. }
  102. void CWebsocketServer::deal_msg(std::string &payload, websocketpp::connection_hdl hdl)
  103. {
  104. boost::lock_guard<boost::mutex> lock(m_dealMsgLock); //在buffer和json处理时,deal_msg会调用多次,导致transId存在重复可能
  105. ::DbgEx("deal_msg :%d, %s", payload.length(), payload.length() > 800 ? payload.substr(0, 800).append("...").c_str() : payload.c_str());
  106. if (chromiumRpcTask::get_mutable_instance().isChromiumRpcWork()) chromiumRpcTask::get_mutable_instance().publishMsg({ generateTimeStr(), payload.c_str() });
  107. auto ret = this->m_serializer->JsonToBuffer(payload);
  108. CMessage *p = ret.second;
  109. if (ret.first == Broadcast && nullptr == p)
  110. {
  111. DbgEx("JsonToBuffer return NULL, perhaps an event happened");
  112. do_sendJsonBroadcast(payload);
  113. return;
  114. }
  115. else if (ret.first == GetSession)
  116. {
  117. cJSON* pJson = cJSON_Parse(payload.c_str());
  118. auto transIdJson = cJSON_GetObjectItem(pJson, "transId");
  119. if (transIdJson != nullptr)
  120. {
  121. int transid = transIdJson->valueint;
  122. auto sessionRet = m_esm->GetAllSessionRequest(transid);
  123. DbgEx("sessionJson:%s", sessionRet.second.c_str());
  124. if (sessionRet.first)
  125. {
  126. auto js = restroreTransId(sessionRet.second);
  127. m_wsserver.send(hdl, js, websocketpp::frame::opcode::TEXT);
  128. }
  129. }
  130. return;
  131. }
  132. else if (ret.first == BeginSession)
  133. storeEntityWithCLass(m_serializer->GetEntityName(payload), m_serializer->GetClassName(payload));
  134. // Try to manage entity session
  135. RequestProcessType processType = this->m_esm->RequestProcess(p, m_serializer->GetEntityName(payload), (long)hdl.lock().get());
  136. switch (processType)
  137. {
  138. case Chromium::PROCESS_NOTHING:
  139. DbgEx("do PROCESS_NOTHING");
  140. return;
  141. case Chromium::PROCESS_SEND:
  142. DbgEx("do PROCESS_SEND");
  143. if (nullptr != p)
  144. WriteToFramework(p);
  145. break;
  146. case Chromium::PROCESS_STARTSESSION:
  147. {
  148. DbgEx("do PROCESS_STARTSESSION");
  149. auto entityName = m_serializer->GetEntityName(payload);
  150. if (entityName == "Chromium")
  151. {
  152. DbgEx("discard, don't make session with chromium");
  153. break;
  154. }
  155. updateMsgPool(entityName, payload, hdl);
  156. do_sendJsonStartSession(entityName, m_serializer->GetClassName(payload));
  157. }
  158. break;
  159. case Chromium::PROCESS_FINDSESSION:
  160. {
  161. DbgEx("do PROCESS_FINDSESSION");
  162. std::string js = m_esm->GetStartSessionAck(p, m_serializer->GetEntityName(payload));
  163. js = restroreTransId(js);
  164. m_wsserver.send(hdl, js, websocketpp::frame::opcode::TEXT);
  165. }
  166. break;
  167. case Chromium::PROCESS_RECORDMSG:
  168. {
  169. DbgEx("do PROCESS_RECORDMSG");
  170. auto entityName = m_serializer->GetEntityName(payload);
  171. updateMsgPool(entityName, payload, hdl);
  172. }
  173. break;
  174. default:
  175. break;
  176. }
  177. }
  178. // websocket message handler
  179. void CWebsocketServer::message_handler(websocketpp::connection_hdl hdl, server::message_ptr msg){
  180. /*
  181. static bool isTest = true;
  182. if (isTest)
  183. {
  184. msg->set_payload("{\"messageType\":13,\"transID\" : 11111,\"name\" : \"UIState\",\"value\" : \"M\"}");
  185. isTest = false;
  186. }
  187. else
  188. return;
  189. */
  190. static int pos = 0;
  191. static std::map<int, int> t_hdlArr;
  192. int hdlPos = (long)hdl.lock().get();
  193. if (t_hdlArr.end() == t_hdlArr.find(hdlPos))
  194. t_hdlArr[hdlPos] = pos++;
  195. auto msgHandleFun = [&]() {
  196. DbgEx("CWebsocketServer -> message_handler");
  197. std::string payload = msg->get_payload();
  198. // proto convert here
  199. cJSON* pJson = cJSON_Parse(payload.c_str());
  200. if (nullptr == pJson) {
  201. DbgEx("CWebsocketServer -> message_handler, jsonErr:%s", payload.c_str());
  202. return;
  203. }
  204. auto transIdJson = cJSON_GetObjectItem(pJson, "transId");
  205. if(transIdJson != nullptr)
  206. {
  207. int transid = transIdJson->valueint;
  208. int modifyT = t_hdlArr[hdlPos] << 24;
  209. int dstTransId = transid ^ modifyT;
  210. cJSON_SetIntValue(transIdJson, dstTransId);
  211. }
  212. std::string dstPayLoad = cJSON_PrintUnformatted(pJson);
  213. deal_msg(dstPayLoad, hdl);
  214. DbgEx("Leave CWebsocketServer -> message_handler");
  215. };
  216. boost::thread dealMsgThread(msgHandleFun);
  217. dealMsgThread.join();
  218. }
  219. std::string CWebsocketServer::restroreTransId(std::string payLoad)
  220. {
  221. cJSON* pJson = cJSON_Parse(payLoad.c_str());
  222. auto transIdJson = cJSON_GetObjectItem(pJson, "transId");
  223. if (transIdJson != nullptr)
  224. {
  225. int transid = transIdJson->valueint;
  226. int dstTransId = transid & 0x00FFFFFF;
  227. cJSON_SetIntValue(transIdJson, dstTransId);
  228. }
  229. return cJSON_PrintUnformatted(pJson);
  230. }
  231. void CWebsocketServer::open_handler(websocketpp::connection_hdl hdl){
  232. // hand shake here
  233. DbgEx("new connection to ws server : %u", hdl.lock().get());
  234. m_connection_hdls.insert(std::pair<unsigned int, websocketpp::connection_hdl>((long)hdl.lock().get(), hdl));
  235. }
  236. void CWebsocketServer::close_handler(websocketpp::connection_hdl hdl){
  237. // hand shake here
  238. auto connectionIter = m_connection_hdls.find((long)hdl.lock().get());
  239. if (m_connection_hdls.end() != connectionIter)
  240. {
  241. DbgEx("connection with ws server closed : %u", hdl.lock().get());
  242. m_connection_hdls.erase(connectionIter);
  243. }
  244. else
  245. DbgEx("connection close erase failed : %u", hdl.lock().get());
  246. }
  247. void CWebsocketServer::do_run(){
  248. DbgEx("CWebsocketServer -> do_run");
  249. // Start the Asio io_service run loop
  250. DbgEx("Start the Asio io_service run loop");
  251. while (true)
  252. {
  253. try
  254. {
  255. m_ios.poll();
  256. Sleep(2);
  257. }
  258. catch (...)
  259. {
  260. DbgEx("other exception in ios poll");
  261. }
  262. }
  263. }
  264. void CWebsocketServer::do_relink()
  265. {
  266. DbgEx("do_relink Enter");
  267. while (true)
  268. {
  269. try
  270. {
  271. Sleep(10000);
  272. DbgEx("try do_relink");
  273. auto unlinkArr = m_esm->queryUnLinkSession();
  274. boost::lock_guard<boost::mutex> lock(m_dealMsgLock);
  275. for (auto it : unlinkArr)
  276. {
  277. auto ret = getEntityClass(it);
  278. if (ret.first)
  279. {
  280. DbgEx("try to relink %s, %s", it.c_str(), ret.second.c_str());
  281. do_sendJsonStartSession(it, ret.second);
  282. }
  283. else
  284. DbgEx("unable find class of entity %s", it.c_str());
  285. }
  286. }
  287. catch (...)
  288. {
  289. DbgEx("exception in do_relink");
  290. }
  291. }
  292. }
  293. void CWebsocketServer::run(){
  294. DbgEx("CWebsocketServer -> run");
  295. boost::thread thread1(boost::bind(&CWebsocketServer::do_run, this));
  296. boost::thread thread2(boost::bind(&CWebsocketServer::do_relink, this));
  297. }
  298. void CWebsocketServer::do_sendJsonBroadcast(std::string js)
  299. {
  300. js = restroreTransId(js);
  301. DbgEx("message broadcast : json = %s", js.c_str());
  302. if (js.empty())
  303. {
  304. DbgEx("string empty");
  305. return;
  306. }
  307. if (m_connection_hdls.empty())
  308. {
  309. DbgEx("message_from_socket : no websocket client connection");
  310. }
  311. else
  312. {//broadcast不进行转换
  313. if (js.empty())
  314. {
  315. DbgEx("string empty 2");
  316. return;
  317. }
  318. DbgEx("do_sendJsonBroadcast Enter...");
  319. for (auto it = m_connection_hdls.begin(); it != m_connection_hdls.end(); it++)
  320. {
  321. try
  322. {
  323. websocketpp::connection_hdl hdl = it->second;
  324. m_wsserver.send(hdl, js, websocketpp::frame::opcode::TEXT);
  325. }
  326. catch (const websocketpp::lib::error_code& e)
  327. {
  328. DbgEx("m_wsserver send crash : error message=%s", e.message());
  329. }
  330. catch (const std::exception &e) {
  331. DbgEx("std exception : %s", e.what());
  332. }
  333. catch (...) {
  334. DbgEx("other exception");
  335. }
  336. }
  337. DbgEx("do_sendJsonBroadcast End...");
  338. }
  339. }
  340. void CWebsocketServer::do_sendJson(std::string js, int hdlID, unsigned int id)
  341. {
  342. js = restroreTransId(js);
  343. DbgEx("WebSocket Search message_from_socket : json = %s", js.c_str());
  344. if (chromiumRpcTask::get_mutable_instance().isChromiumRpcWork()) chromiumRpcTask::get_mutable_instance().publishMsg({ generateTimeStr(), "do_sendJson---------" + js });
  345. if (js.empty())
  346. {
  347. DbgEx("string empty");
  348. return;
  349. }
  350. if (m_connection_hdls.empty())
  351. DbgEx("message_from_socket : no websocket client connection");
  352. else {
  353. #if(defined _WIN32 || defined _WIN64)
  354. js = string_to_utf8(js);
  355. #endif
  356. if (js.empty())
  357. {
  358. DbgEx("string empty 2");
  359. return;
  360. }
  361. try
  362. {
  363. DbgEx("do_sendJson Enter...");
  364. std::map<unsigned int, websocketpp::connection_hdl>::iterator it = m_connection_hdls.find(hdlID);
  365. if (m_connection_hdls.end() != it)
  366. {
  367. DbgEx("Send....");
  368. websocketpp::connection_hdl hdl = it->second;
  369. m_wsserver.send(hdl, js, websocketpp::frame::opcode::TEXT);
  370. }
  371. else {
  372. DbgEx("ws connection handler not found! id = %u", id);
  373. }
  374. DbgEx("do_sendJson End...");
  375. }
  376. catch (const websocketpp::lib::error_code& e)
  377. {
  378. DbgEx("m_wsserver send crash : error message=%s", e.message());
  379. }
  380. catch (const std::exception &e) {
  381. DbgEx("std exception : %s", e.what());
  382. FILE* fp = NULL;
  383. fp = fopen("chromiumTmp", "a+");
  384. if (fp == NULL)
  385. return;
  386. int res = fprintf(fp, "%s\n", js.c_str());
  387. fclose(fp);
  388. }
  389. catch (...) {
  390. DbgEx("other exception");
  391. }
  392. }
  393. }
  394. // socket message handler
  395. void CWebsocketServer::message_from_socket(CMessage& msg, unsigned int id){
  396. // get message from socket and deserialize
  397. // then send back to the web client
  398. auto bufferLength = msg.getBufferLength();
  399. if(bufferLength > MAX_TRANSFER_LEN)
  400. DbgEx("WebSocket Search message_from_socket : buffer len = %d, buffer pre50:%s", msg.getBufferLength(), msg.printfHEX(50).c_str());
  401. else
  402. DbgEx("WebSocket Search message_from_socket : buffer len = %d", msg.getBufferLength());
  403. if (chromiumRpcTask::get_mutable_instance().isChromiumRpcWork()) chromiumRpcTask::get_mutable_instance().publishMsg({ generateTimeStr(), "message_from_socket---------" + msg.printfHEX() });
  404. int replaceTransId = 0;
  405. if (msg.getLength() > 16 && m_esm != NULL)
  406. {//this is return buffer, it would not send out again, so I exchange the transId and sessionId place
  407. msg.exchangeSessionIdAndTransId();
  408. auto tmpReplace = m_esm->getSrcTransID(msg.getTransID());
  409. replaceTransId = tmpReplace.first == true ? tmpReplace.second : 0;
  410. }
  411. // 处理session ack,获取hdlID
  412. unsigned int hdlID = 0;
  413. std::vector<std::pair<int, int>> sendArr;
  414. if (8 == msg.getMessageType())
  415. {
  416. m_esm->AskProcessEvent(&msg, sendArr);
  417. if (sendArr.size() == 0)
  418. m_esm->AskProcessEvent(&msg, sendArr);
  419. for (auto i = sendArr.begin(); i != sendArr.end(); i++)
  420. {
  421. msg.setTransID(i->first);
  422. std::string js = this->m_serializer->BufferToJson(msg);
  423. do_sendJson(js, i->second, id);
  424. }
  425. }
  426. else if (2 == msg.getMessageType()) //session end
  427. {
  428. int sessionId = msg.getTransID();
  429. auto ret = m_esm->DoSessionRemove(sessionId);
  430. if (ret.first)
  431. DbgEx("detect session %s:%d lost!remove success", ret.second.c_str(), sessionId);
  432. else
  433. DbgEx("detect session %d lost!remove failed", sessionId);
  434. }
  435. else if (5 == msg.getMessageType())
  436. {//sessionAck
  437. auto ret = m_esm->AskProcessSession(&msg, hdlID);
  438. auto sessionId = msg.getSessionID();
  439. if (ACKPROCESS_NOTHING == ret.first)
  440. {
  441. DbgEx("can not find save session, process noting, %s", ret.second.c_str());//error
  442. return;
  443. }
  444. if (0 != hdlID)
  445. {//hdlId为0时,说明本地发起的session
  446. std::string js = this->m_serializer->BufferToJson(msg, replaceTransId);
  447. do_sendJson(js, hdlID, id); //发给首记录的CMessage
  448. }
  449. for (auto cur = m_msg_pool.begin(); cur != m_msg_pool.end() && -1 != sessionId;cur++)
  450. {//sessionId为-1时需处理,否则会引发消息风暴
  451. if (cur->first == ret.second)
  452. {
  453. std::vector<std::pair<websocketpp::connection_hdl, std::string>> msgArr(cur->second);
  454. m_msg_pool.erase(cur); //为防止处理消息时引发消息风暴,拷贝并删除原msg_pool
  455. DbgEx("Session with %s Make, deal with record Msg:%d", ret.second.c_str(), msgArr.size());
  456. for (auto msg = msgArr.begin(); msg != msgArr.end(); msg++)
  457. deal_msg(msg->second, msg->first);
  458. break;
  459. }
  460. }
  461. }
  462. else
  463. {
  464. m_esm->AckProcess(&msg, hdlID);
  465. std::string js = this->m_serializer->BufferToJson(msg, replaceTransId);
  466. do_sendJson(js, hdlID, id);
  467. }
  468. }
  469. void CWebsocketServer::init_websocket(){
  470. auto checkPortExist = []() -> bool {
  471. boost::asio::io_service ioService;
  472. boost::asio::ip::tcp::socket* pSockTcp = NULL;
  473. bool bSockUseError = false;
  474. try {
  475. auto tcpEndpoint = boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), DEFAULT_SERVER_PORT);
  476. pSockTcp = new boost::asio::ip::tcp::socket(ioService, tcpEndpoint);
  477. bSockUseError = false;
  478. }
  479. catch (...)
  480. {
  481. bSockUseError = true;
  482. }
  483. //释放
  484. if (!bSockUseError && pSockTcp != NULL)
  485. {
  486. delete pSockTcp;
  487. pSockTcp = NULL;
  488. }
  489. ioService.stop();
  490. return bSockUseError;
  491. };
  492. /*
  493. while (true) {
  494. if (!checkPortExist())
  495. break;
  496. else
  497. DbgEx("checkPortExist failed");
  498. std::this_thread::sleep_for(std::chrono::seconds(5));
  499. }
  500. */
  501. try
  502. {
  503. // Set logging settings
  504. DbgEx("Set logging settings");
  505. m_wsserver.set_error_channels(websocketpp::log::elevel::all);
  506. m_wsserver.set_access_channels(websocketpp::log::alevel::all ^ websocketpp::log::alevel::frame_payload);
  507. DbgEx("m_wsserver.get_max_message_size = %d", m_wsserver.get_max_message_size());
  508. m_wsserver.set_max_message_size(MAX_TRANSFER_LEN);
  509. m_wsserver.set_close_handshake_timeout(3000);
  510. m_wsserver.set_pong_timeout(3000);
  511. // Initialize Asio
  512. DbgEx("Initialize Asio");
  513. m_wsserver.init_asio(&m_ios);
  514. // Set the default message handler to the echo handler
  515. DbgEx("Set the default message handler to the echo handler");
  516. m_wsserver.set_message_handler(websocketpp::lib::bind(&CWebsocketServer::message_handler, this, websocketpp::lib::placeholders::_1, websocketpp::lib::placeholders::_2));
  517. DbgEx("Set set_open_handler");
  518. m_wsserver.set_open_handler(websocketpp::lib::bind(&CWebsocketServer::open_handler, this, websocketpp::lib::placeholders::_1));
  519. m_wsserver.set_close_handler(websocketpp::lib::bind(&CWebsocketServer::close_handler, this, websocketpp::lib::placeholders::_1));
  520. // Listen on port 9002
  521. m_wsserver.listen(DEFAULT_SERVER_PORT);
  522. // Queues a connection accept operation
  523. DbgEx("Queues a connection accept operation");
  524. m_wsserver.start_accept();
  525. m_initSuccess = true;
  526. DbgEx("do_run end");
  527. } catch (websocketpp::exception const & e) {
  528. DbgEx("websocketpp exception %s ", e.what());
  529. m_initSuccess = false;
  530. } catch (...) {
  531. DbgEx("other exception");
  532. m_initSuccess = false;
  533. }
  534. }
  535. void CWebsocketServer::myTest()
  536. {
  537. // using namespace IEBrowser;
  538. // IEBrowserSrv_ClientBase *pClient = new IEBrowserSrv_ClientBase(this->m_pEntity);
  539. // auto rc = pClient->Connect();
  540. // if (Error_Succeed != rc)
  541. // DbgEx("connect to IEBrowser entity fail: %d", rc);
  542. // else
  543. // DbgEx("connect to IEBrowser entity success");
  544. }
  545. #if(defined _WIN32 || defined _WIN64)
  546. std::string CWebsocketServer::string_to_utf8(const std::string & str) {
  547. LOG_FUNCTION();
  548. DbgEx("start string_to_utf8...");
  549. int wcLen = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);
  550. DbgEx("wcLen = %d", wcLen);
  551. if(wcLen > 0) {
  552. WCHAR* pwBuf = new WCHAR[wcLen + 1];
  553. if(pwBuf == NULL) {
  554. return std::string();
  555. }
  556. memset(pwBuf, 0, sizeof(WCHAR)*(wcLen + 1));
  557. wcLen = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, pwBuf, wcLen);
  558. if(wcLen <= 0) {
  559. delete[] pwBuf;
  560. return std::string();
  561. }
  562. int ucLen = WideCharToMultiByte(CP_UTF8, 0, pwBuf, -1, NULL, 0, NULL, NULL);
  563. DbgEx("ucLen = %d", ucLen);
  564. if(ucLen < 0) {
  565. delete[] pwBuf;
  566. return std::string();
  567. }
  568. char* pBuf = new char[ucLen + 1];
  569. if(pBuf == NULL) {
  570. delete pwBuf;
  571. return std::string();
  572. }
  573. memset(pBuf, 0, sizeof(char)*(ucLen + 1));
  574. ucLen = WideCharToMultiByte(CP_UTF8, 0, pwBuf, -1, pBuf, ucLen, NULL, NULL);
  575. if (ucLen <= 0) {
  576. delete[] pwBuf;
  577. delete[] pBuf;
  578. return std::string();
  579. }
  580. std::string retStr(pBuf);
  581. DbgEx("string_to_utf8 return: %s",retStr.c_str());
  582. if(pwBuf) {
  583. delete[] pwBuf;
  584. pwBuf = NULL;
  585. }
  586. if(pBuf) {
  587. delete[] pBuf;
  588. pBuf = NULL;
  589. }
  590. return retStr;
  591. }
  592. return std::string();
  593. }
  594. #endif
  595. void CWebsocketServer::init_entity_sessions(){
  596. return;
  597. }
  598. }