#include "CClientSession.h" #include "CServer.h" #include 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) { try { socket_.write_some(boost::asio::buffer(msg.c_str(), msg.length() + 1)); } catch (const std::exception& e) { std::string err = e.what(); //先把socket关闭掉 socket_.close(); //可能客户端关掉了socket if (m_username == "") { //说明这个socket还没获取过用户名 delete this; } else { //这种是已经绑定过用户名了 this->stop(); m_server->DeleteClient(m_username); } } } 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(); std::string is_login = document["is_login"].GetString(); //这个用于判断是否成功绑定用户名了 m_username = username; //获取到用户名了,进行绑定 m_server->BindUsername(username, this); //绑定完了检查这个用户有没有离线消息 if (is_login == "1") { m_server->CheckOfflineMessage(username); } //处理完了,重新读取 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_.close(); //可能客户端关掉了socket if (m_username == "") { //说明这个socket还没获取过用户名 delete this; } else { //这种是已经绑定过用户名了 this->stop(); m_server->DeleteClient(m_username); } } }