#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::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(); //获取到用户名了,进行绑定 m_server->BindUsername(username, this); //返回ok给客户端 rapidjson::Document doc; doc.SetObject(); rapidjson::Document::AllocatorType &allocator = doc.GetAllocator(); //获取分配器 doc.AddMember("type", 0, allocator); doc.AddMember("status", "ok", allocator); rapidjson::StringBuffer buffer; rapidjson::Writer writer(buffer); doc.Accept(writer); //返回给接入层的消息 std::string ok_msg = buffer.GetString(); boost::asio::async_write(socket_, boost::asio::buffer(ok_msg.c_str(), ok_msg.length()), boost::bind(&CClientSession::handle_write, this, boost::asio::placeholders::error)); //处理完了,重新读取 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 { delete this; } } void CClientSession::handle_write(const boost::system::error_code& error) { if(!error) { } else { delete this; } }