CClientSession.cpp 2.6 KB

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