| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- #include "CClientSession.h"
- #include "CServer.h"
- CClientSession::~CClientSession()
- {
- }
- void CClientSession::start()
- {
- socket_.async_read_some(boost::asio::buffer(data_, max_length),
- boost::bind(&CClientSession::handle_read, this,
- boost::asio::placeholders::error,
- boost::asio::placeholders::bytes_transferred));
- }
- void CClientSession::stop()
- {
- socket_.close();
- delete this;
- }
- void CClientSession::send_message(std::string msg)
- {
- boost::asio::async_write(socket_,
- boost::asio::buffer(msg.c_str(), msg.length()),
- boost::bind(&CClientSession::handle_write, this,
- boost::asio::placeholders::error));
- }
- void CClientSession::SetServer(CServer* server)
- {
- m_server = server;
- }
- void CClientSession::handle_read(const boost::system::error_code& error,
- size_t bytes_transferred)
- {
- if(!error)
- {
- //读到客户端发过来的内容,进行绑定
- std::string msg = data_;
- rapidjson::Document document;
- document.Parse(msg.c_str());
- if(!document.IsObject())
- {
- LOG_INFO("message 非法!");
- return;
- }
- std::string username = document["username"].GetString();
- std::string timestamp = document["timestamp"].GetString();
- m_username = username;
- //获取到用户名了,进行绑定
- m_server->BindUsername(username, this);
- //处理完了,重新读取
- memset(data_, 0, max_length);
- socket_.async_read_some(boost::asio::buffer(data_, max_length),
- boost::bind(&CClientSession::handle_read, this,
- boost::asio::placeholders::error,
- boost::asio::placeholders::bytes_transferred));
- }
- else
- {
- //可能客户端关掉了socket
- if (m_username == "")
- {
- //说明这个socket还没获取过用户名
- delete this;
- }
- else
- {
- //这种是已经绑定过用户名了
- this->stop();
- m_server->DeleteClient(m_username);
- }
- }
- }
- void CClientSession::handle_write(const boost::system::error_code& error)
- {
- if(!error)
- {
- //消息发送成功,继续查询是否有离线消息
- }
- else
- {
- //可能客户端关掉了socket
- if (m_username == "")
- {
- //说明这个socket还没获取过用户名
- delete this;
- }
- else
- {
- //这种是已经绑定过用户名了
- this->stop();
- m_server->DeleteClient(m_username);
- }
- }
- }
|