#ifndef CHAT_MESSAGE_HPP
#define CHAT_MESSAGE_HPP
#include
#include
#include
#include
#include
#include "structHeader.hpp"
class chat_message
{
public:
enum { header_length = sizeof(Header) };
enum { max_body_length = 512 };
chat_message()
{
}
const char* data() const
{
return data_;
}
char* data()
{
return data_;
}
size_t length() const
{
return header_length + m_header.bodySize;
}
const char* body() const
{
return data_ + header_length;
}
char* body()
{
return data_ + header_length;
}
int type(){
return m_header.type;
}
size_t body_length() const
{
return m_header.bodySize;
}
void setMessage(int messageType, const void *buffer, size_t bufferSize){
assert(bufferSize <= max_body_length);
m_header.bodySize = (int)bufferSize;
m_header.type = messageType;
std::memcpy(body(), buffer, bufferSize);
std::memcpy(data(), &m_header, header_length);
}
void setMessage(int messageType, const std::string& buffer){
setMessage(messageType, buffer.data(), buffer.size());
}
bool decode_header()
{
std::memcpy(&m_header, data(), header_length);
if (m_header.bodySize > max_body_length) {
std::cout << "body size " << m_header.bodySize << " " << m_header.type << std::endl;
return false;
}
return true;
}
private:
char data_[header_length + max_body_length];
Header m_header;
};
#endif // CHAT_MESSAGE_HPP
//
// chat_message.cpp
// ServerOfChat
//
// Created by ma qianli on 2020/3/4.
// Copyright © 2020 qianli. All rights reserved.
//
#include "chat_message.hpp"
///
//
// JsonObject.hpp
// ClientOfChat
//
// Created by ma qianli on 2020/3/12.
// Copyright © 2020 qianli. All rights reserved.
//
#ifndef JsonObject_hpp
#define JsonObject_hpp
#include
#include
#include
#include
#include
using ptree = boost::property_tree::ptree;
inline std::string ptreeToJsonString(const ptree& tree){
std::stringstream ss;
boost::property_tree::write_json(ss, tree, false);
return ss.str();
}
#endif /* JsonObject_hpp */
//
// JsonObject.cpp
// ClientOfChat
//
// Created by ma qianli on 2020/3/12.
// Copyright © 2020 qianli. All rights reserved.
//
#include "JsonObject.hpp"
///
//
// SerilizationObject.hpp
// ClientOfChat
//
// Created by ma qianli on 2020/3/11.
// Copyright © 2020 qianli. All rights reserved.
//
#ifndef SerilizationObject_hpp
#define SerilizationObject_hpp
#include
#include
#include
class SBindName {
friend class boost::serialization::access;
template
void serialize(Archive &ar, const unsigned int version){
ar & m_bindName;
}
std::string m_bindName;
public:
SBindName(std::string name):m_bindName(std::move(name)){}
SBindName(){}
const std::string& bindName()const{
return m_bindName;
}
};
class SChatInfo {
friend class boost::serialization::access;
template
void serialize(Archive &ar, const unsigned int version){
ar & m_chatInformation;
}
std::string m_chatInformation;
public:
SChatInfo(std::string info):m_chatInformation(std::move(info)){}
SChatInfo(){}
const std::string& chatInformation()const{
return m_chatInformation;
}
};
class SRoomInfo {
friend class boost::serialization::access;
template
void serialize(Archive &ar, const unsigned int version){
ar & m_bind;
ar & m_chat;
}
SBindName m_bind;
SChatInfo m_chat;
public:
SRoomInfo(){}
SRoomInfo(std::string name, std::string info):
m_bind(std::move(name)), m_chat(std::move(info)){}
const std::string& bindName()const{
return m_bind.bindName();
}
const std::string& chatInformation()const{
return m_chat.chatInformation();
}
};
#endif /* SerilizationObject_hpp */
//
// SerilizationObject.cpp
// ClientOfChat
//
// Created by ma qianli on 2020/3/11.
// Copyright © 2020 qianli. All rights reserved.
//
#include "SerilizationObject.hpp"
//
// structHeader.hpp
// ServerOfChat
//
// Created by ma qianli on 2020/3/11.
// Copyright © 2020 qianli. All rights reserved.
//
#ifndef structHeader_hpp
#define structHeader_hpp
#include
#include
struct Header {
int bodySize;
int type;
};
//client send
struct BindName {
char name[32];
int nameLen;
};
//client send
struct ChatInformation {
char information[256];
int infolen;
};
//server send
struct RoomInformation {
BindName name;
ChatInformation chat;
};
bool parseMessage(const std::string& input, int *type, std::string& outbuffer);
bool parseMessage2(const std::string& input, int *type, std::string& outbuffer);
bool parseMessage3(const std::string& input, int *type, std::string& outbuffer);
#endif /* structHeader_hpp */
//
// structHeader.cpp
// ServerOfChat
//
// Created by ma qianli on 2020/3/11.
// Copyright © 2020 qianli. All rights reserved.
//
#include "structHeader.hpp"
#include "SerilizationObject.hpp"
#include "JsonObject.hpp"
#include
#include
#include
#include
//cmd messagebody
bool parseMessage(const std::string& input, int *type, std::string& outbuffer){
auto pos = input.find_first_of(" ");
if (pos == std::string::npos) {
return false;
}
if (pos == 0) {
return false;
}
auto cmd = input.substr(0, pos);//[)
if (cmd == "BindName") {
std::string name = input.substr(pos + 1);
if (name.size() > 32) {
return false;
}
if (type) {
*type = 1;
}
BindName bindName;
bindName.nameLen = (int)name.size();
std::memcpy(&bindName, name.data(), name.size());
//std::strcpy(bindName.name, name.c_str());
auto buffer = (char*)(&bindName);
outbuffer.assign(buffer, sizeof(bindName));
return true;
}else if (cmd == "Chat"){
std::string chat = input.substr(pos + 1);
if (chat.size() > 256) {
return false;
}
if (type) {
*type = 2;
}
ChatInformation chatInfo;
chatInfo.infolen = (int)chat.size();
std::memcpy(&chatInfo, chat.data(), chat.size());
auto buffer = (char*)(&chatInfo);
outbuffer.assign(buffer, sizeof(chatInfo));
return true;
}
return false;
}
template
std::string serialize(const T &obj){
std::stringstream ss;
boost::archive::text_oarchive oa(ss);
oa & obj;//归档到ss中
return ss.str();
}
bool parseMessage2(const std::string& input, int *type, std::string& outbuffer){
auto pos = input.find_first_of(" ");
if (pos == std::string::npos) {
return false;
}
if (pos == 0) {
return false;
}
auto cmd = input.substr(0, pos);//[)
if (cmd == "BindName") {
std::string name = input.substr(pos + 1);
if (name.size() > 32) {
return false;
}
if (type) {
*type = 1;
}
outbuffer = serialize(SBindName(std::move(name)));
return true;
}else if (cmd == "Chat"){
std::string chat = input.substr(pos + 1);
if (chat.size() > 256) {
return false;
}
if (type) {
*type = 2;
}
outbuffer = serialize(SChatInfo(std::move(chat)));
return true;
}
return false;
}
bool parseMessage3(const std::string& input, int *type, std::string& outbuffer){
auto pos = input.find_first_of(" ");
if (pos == std::string::npos) {
return false;
}
if (pos == 0) {
return false;
}
auto cmd = input.substr(0, pos);//[)
if (cmd == "BindName") {
std::string name = input.substr(pos + 1);
if (name.size() > 32) {
return false;
}
if (type) {
*type = 1;
}
ptree tree;
tree.put("name", name);
outbuffer = ptreeToJsonString(tree);
return true;
}else if (cmd == "Chat"){
std::string chat = input.substr(pos + 1);
if (chat.size() > 256) {
return false;
}
if (type) {
*type = 2;
}
ptree tree;
tree.put("information", chat);
outbuffer = ptreeToJsonString(tree);
return true;
}
return false;
}
/
//下面服务端main.cpp
#include
#include
#include
#include
#include
#include
#include "chat_message.hpp"
#include "SerilizationObject.hpp"
#include "JsonObject.hpp"
using boost::asio::ip::tcp;
//----------------------------------------------------------------------
using chat_message_queue = std::deque;
//----------------------------------------------------------------------
class chat_participant
{
public:
virtual ~chat_participant() {}
virtual void deliver(const chat_message& msg) = 0;
};
using chat_participant_ptr = std::shared_ptr ;
//----------------------------------------------------------------------
class chat_room
{
public:
void join(chat_participant_ptr participant)
{
participants_.insert(participant);
for (const auto& msg : recent_msgs_) {
participant->deliver(msg);
}
}
void leave(chat_participant_ptr participant)
{
participants_.erase(participant);
}
void deliver(const chat_message& msg)
{
recent_msgs_.push_back(msg);
while (recent_msgs_.size() > max_recent_msgs)
recent_msgs_.pop_front();
for (auto& participant : participants_) {
participant->deliver(msg);
}
}
private:
std::set participants_;
enum { max_recent_msgs = 100 };
chat_message_queue recent_msgs_;
};
//----------------------------------------------------------------------
class chat_session
: public chat_participant,
public std::enable_shared_from_this
{
public:
chat_session(tcp::socket socket, chat_room& room)
: socket_(std::move(socket)),
room_(room)
{
}
tcp::socket& socket()
{
return socket_;
}
void start()
{
room_.join(shared_from_this());
do_read_header();
}
void deliver(const chat_message& msg)
{
bool write_in_progress = !write_msgs_.empty();
write_msgs_.push_back(msg);
if (!write_in_progress)
{
do_write();
}
}
void do_read_header(){
auto self(shared_from_this());
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.data(), chat_message::header_length),
[this, self](boost::system::error_code ec, std::size_t length){
if (!ec && read_msg_.decode_header()) {
do_read_body();
}else{
room_.leave(shared_from_this());
}
});
}
void do_read_body(){
auto self(shared_from_this());
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.body(),read_msg_.body_length()),
[this, self](boost::system::error_code ec, std::size_t length){
if (!ec) {
//room_.deliver(read_msg_);
handleMessage();
do_read_header();
} else {
room_.leave(shared_from_this());
}
});
}
ptree toPtree(){
ptree obj;
std::string buffer = std::string(read_msg_.body(), read_msg_.body_length());
std::stringstream ss(buffer);
boost::property_tree::read_json(ss, obj);//从流读取到对象(这里的对象,有点像NSObject中NSArray、NSDictionary对象)
return obj;
}
void handleMessage(){
if (read_msg_.type() == 1) {
auto nameTree = toPtree();
m_name = nameTree.get("name");
std::cout << "shoudaoname " << m_name << std::endl;
}else if (read_msg_.type() == 2){
auto chat = toPtree();
m_chatInformation = chat.get("information");
std::cout << "information " << m_chatInformation << std::endl;
auto rinfo = buildRoomInfo();
chat_message msg;
msg.setMessage(3, rinfo);
room_.deliver(msg);
}
}
std::string buildRoomInfo()const{
ptree tree;
tree.put("name", m_name);
tree.put("information", m_chatInformation);
return ptreeToJsonString(tree);
}
void do_write(){
auto self(shared_from_this());
boost::asio::async_write(socket_,
boost::asio::buffer(write_msgs_.front().data(), write_msgs_.front().length()),
[this, self](boost::system::error_code ec, std::size_t length){
if (!ec) {
write_msgs_.pop_front();
if (!write_msgs_.empty()) {
do_write();
}
} else {
room_.leave(shared_from_this());
}
});
}
private:
std::string m_name;
std::string m_chatInformation;
tcp::socket socket_;
chat_room& room_;
chat_message read_msg_;
chat_message_queue write_msgs_;
};
typedef boost::shared_ptr chat_session_ptr;
//----------------------------------------------------------------------
class chat_server
{
public:
chat_server(boost::asio::io_service& io_service,
const tcp::endpoint& endpoint)
: socket_(io_service),
acceptor_(io_service, endpoint)
{
do_accept();
}
void do_accept(){
acceptor_.async_accept(socket_, [this](boost::system::error_code ec){
if (!ec) {
std::make_shared(std::move(socket_), room_)->start();
}
do_accept();
});
}
private:
tcp::socket socket_;
tcp::acceptor acceptor_;
chat_room room_;
};
typedef boost::shared_ptr chat_server_ptr;
typedef std::list chat_server_list;
//----------------------------------------------------------------------
int main(int argc, char* argv[])
{
try
{
if (argc < 2)
{
std::cerr << "Usage: chat_server [ ...]\n";
return 1;
}
boost::asio::io_service io_service;
std::list servers;
for (int i = 1; i < argc; ++i) {
tcp::endpoint endpoint(tcp::v4(), std::atoi(argv[i]));
servers.push_back(new chat_server(io_service, endpoint));
}
io_service.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
/
//下面客户端main.cpp
#include
#include
#include
#include
#include
#include "chat_message.hpp"
#include "SerilizationObject.hpp"
#include "JsonObject.hpp"
using boost::asio::ip::tcp;
using chat_message_queue = std::deque;
class chat_client{
boost::asio::io_service &m_io_service;
tcp::socket m_socket;
chat_message m_read_msg;
chat_message_queue m_write_msgs;
public:
chat_client(boost::asio::io_service &io_service,
tcp::resolver::iterator endpoint_iterator):
m_io_service(io_service), m_socket(io_service){
do_connect(endpoint_iterator);
}
void write(const chat_message &msg){
//让lambda在m_io_service的run所在线程执行(类似于OC中的performSelector: onThread: withObject: waitUntilDone: modes:)
m_io_service.post([this, msg](){
bool write_in_progress = !m_write_msgs.empty();
m_write_msgs.push_back(msg);
if (!write_in_progress) {
do_write();
}
});
}
void close(){
m_io_service.post([this](){
m_socket.close();
});
}
void do_connect(tcp::resolver::iterator endpoint_iterator){
boost::asio::async_connect(m_socket, endpoint_iterator,
[this](boost::system::error_code ec, tcp::resolver::iterator it){
if (!ec) {
do_read_header();
}
});
}
void do_read_header(){
boost::asio::async_read(m_socket,
boost::asio::buffer(m_read_msg.data(), chat_message::header_length),
[this](boost::system::error_code ec, std::size_t lenght){
if (!ec && m_read_msg.decode_header()) {
do_read_body();
}else{
m_socket.close();
}
});
}
void do_read_body(){
boost::asio::async_read(m_socket,
boost::asio::buffer(m_read_msg.body(), m_read_msg.body_length()),
[this](boost::system::error_code ec, std::size_t length){
if (!ec) {
if (m_read_msg.type() == 3) {
std::stringstream ss(std::string(m_read_msg.body(), m_read_msg.body() +
m_read_msg.body_length()));
std::cout << "receive from server: " << ss.str() << std::endl;
ptree tree;
boost::property_tree::read_json(ss, tree);//从流中读取到tree
std::cout << "client: '";
std::cout << tree.get("name");
std::cout << "' says '";
std::cout << tree.get("information");
std::cout << "'" << std::endl;
}
//继续读取下一条信息的头
do_read_header();
}else{
m_socket.close();
}
});
}
void do_write(){
boost::asio::async_write(m_socket, boost::asio::buffer(m_write_msgs.front().data(), m_write_msgs.front().length()),
[this](boost::system::error_code ec, std::size_t length){
if (!ec) {
m_write_msgs.pop_front();
if (!m_write_msgs.empty()) {
do_write();
}
}else{
m_socket.close();
}
});
}
};
int main(int argc, const char * argv[]) {
try {
if (argc != 3) {
std::cerr << "Usage: chat_client \n";
return 1;
}
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
auto endpoint_iterator = resolver.resolve({argv[1], argv[2]});
chat_client c(io_service, endpoint_iterator);
std::thread t([&io_service](){
io_service.run();//这样,与io_service绑定的事件源的回调均在子线程上执行(这里指的是boost::asio::async_xxx中的lambda函数)。
});
char line[chat_message::max_body_length + 1] = "";
while (std::cin.getline(line, chat_message::max_body_length + 1)) {
chat_message msg;
auto type = 0;
std::string input(line, line + std::strlen(line));
std::string output;
if (parseMessage3(input, &type, output)) {
msg.setMessage(type, output.data(), output.size());
c.write(msg);
std::cout << "write message for server" << output.size() << std::endl;
}
}
c.close();
//这里必须close,否则子线程中run不会退出,
//因为boost::asio::async_read事件源一直注册在io_service中.
t.join();
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
}
return 0;
}