CClientSession.cpp 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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::send_message(std::string msg)
  14. {
  15. boost::asio::async_write(socket_,
  16. boost::asio::buffer(msg.c_str(), msg.length()),
  17. boost::bind(&CClientSession::handle_write, this,
  18. boost::asio::placeholders::error));
  19. }
  20. void CClientSession::SetServer(CServer* server)
  21. {
  22. m_server = server;
  23. }
  24. void CClientSession::handle_read(const boost::system::error_code& error,
  25. size_t bytes_transferred)
  26. {
  27. if(!error)
  28. {
  29. //读到客户端发过来的内容,进行绑定
  30. std::string msg = data_;
  31. rapidjson::Document document;
  32. document.Parse(msg.c_str());
  33. if(!document.IsObject())
  34. {
  35. LOG_INFO("message 非法!");
  36. return;
  37. }
  38. std::string username = document["username"].GetString();
  39. //获取到用户名了,进行绑定
  40. m_server->BindUsername(username, this);
  41. //返回ok给客户端
  42. rapidjson::Document doc;
  43. doc.SetObject();
  44. rapidjson::Document::AllocatorType &allocator = doc.GetAllocator(); //获取分配器
  45. doc.AddMember("type", 0, allocator);
  46. doc.AddMember("status", "ok", allocator);
  47. rapidjson::StringBuffer buffer;
  48. rapidjson::Writer<StringBuffer> writer(buffer);
  49. doc.Accept(writer);
  50. //返回给接入层的消息
  51. std::string ok_msg = buffer.GetString();
  52. boost::asio::async_write(socket_,
  53. boost::asio::buffer(ok_msg.c_str(), ok_msg.length()),
  54. boost::bind(&CClientSession::handle_write, this,
  55. boost::asio::placeholders::error));
  56. //处理完了,重新读取
  57. memset(data_, 0, max_length);
  58. socket_.async_read_some(boost::asio::buffer(data_, max_length),
  59. boost::bind(&CClientSession::handle_read, this,
  60. boost::asio::placeholders::error,
  61. boost::asio::placeholders::bytes_transferred));
  62. }
  63. else
  64. {
  65. delete this;
  66. }
  67. }
  68. void CClientSession::handle_write(const boost::system::error_code& error)
  69. {
  70. if(!error)
  71. {
  72. }
  73. else
  74. {
  75. delete this;
  76. }
  77. }