CClientSession.cpp 2.7 KB

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