CClientSession.cpp 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. #include "CClientSession.h"
  2. #include "CServer.h"
  3. #include <sqlite3/sqlite3.h>
  4. #include "PosMessage.h"
  5. CClientSession::~CClientSession()
  6. {
  7. }
  8. void CClientSession::start()
  9. {
  10. boost::asio::async_read(socket_, boost::asio::buffer(&m_pos_message, sizeof(PosMessage)),
  11. boost::bind(&CClientSession::handle_read, this,
  12. boost::asio::placeholders::error,
  13. boost::asio::placeholders::bytes_transferred));
  14. }
  15. void CClientSession::stop()
  16. {
  17. socket_.close();
  18. delete this;
  19. }
  20. void CClientSession::send_message(std::string msg)
  21. {
  22. try
  23. {
  24. PosMessage new_msg;
  25. new_msg.m_length = msg.length();
  26. memcpy(new_msg.data, msg.c_str(), msg.length());
  27. new_msg.data[new_msg.m_length] = '\0';
  28. socket_.write_some(boost::asio::buffer(&new_msg, sizeof(PosMessage)));
  29. }
  30. catch (const std::exception& e)
  31. {
  32. std::string err = e.what();
  33. //先把socket关闭掉
  34. socket_.close();
  35. //可能客户端关掉了socket
  36. if (m_username == "")
  37. {
  38. //说明这个socket还没获取过用户名
  39. delete this;
  40. }
  41. else
  42. {
  43. //这种是已经绑定过用户名了
  44. this->stop();
  45. m_server->DeleteClient(m_username);
  46. }
  47. }
  48. }
  49. void CClientSession::SetServer(CServer* server)
  50. {
  51. m_server = server;
  52. }
  53. void CClientSession::handle_read(const boost::system::error_code& error,
  54. size_t bytes_transferred)
  55. {
  56. if(!error)
  57. {
  58. //读到客户端发过来的内容,进行绑定
  59. std::string msg = m_pos_message.data;
  60. rapidjson::Document document;
  61. document.Parse(msg.c_str());
  62. if(!document.IsObject())
  63. {
  64. LOG_INFO("message 非法!");
  65. return;
  66. }
  67. std::string username = document["username"].GetString();
  68. std::string timestamp = document["timestamp"].GetString();
  69. std::string is_login = document["is_login"].GetString();
  70. //这个用于判断是否成功绑定用户名了
  71. m_username = username;
  72. //获取到用户名了,进行绑定
  73. m_server->BindUsername(username, this);
  74. //绑定完了检查这个用户有没有离线消息
  75. if (is_login == "1")
  76. {
  77. m_server->CheckOfflineMessage(username);
  78. }
  79. //处理完了,重新读取
  80. socket_.async_read_some(boost::asio::buffer(&m_pos_message, sizeof(PosMessage)),
  81. boost::bind(&CClientSession::handle_read, this,
  82. boost::asio::placeholders::error,
  83. boost::asio::placeholders::bytes_transferred));
  84. }
  85. else
  86. {
  87. socket_.close();
  88. //可能客户端关掉了socket
  89. if (m_username == "")
  90. {
  91. //说明这个socket还没获取过用户名
  92. delete this;
  93. }
  94. else
  95. {
  96. //这种是已经绑定过用户名了
  97. this->stop();
  98. m_server->DeleteClient(m_username);
  99. }
  100. }
  101. }