使用boost::archive库序列化改进聊天程序

缺陷,
1、CMakeLists.txt文件仍然有点烂,实在没时间修。要多复习点东西
2、用于表征消息头的消息体仍然是C++ struct类型。因为要传递固定长度的头信息。这样双方通信还是只能走C++模式。另一个问题是,决定使用boost::archive库进行序列化和反序列化,也必然导致客户端和服务端只能使用C++模式。

优势,
1、消息体中可以传任意类型的对象,只要将boost::serialization::access对象作为友元传入,并实现模板化的archive方法即可。并不局限于POD类型。boost::archive库帮忙完成了字节对齐等工作。
2、编码简单,不需要频繁使用std::memcpy这样底层的操作。直接使用boost::archive::text_iarchive和boost::archive::text_oarchive进行序列化和反序列化即可。同时也避免了reinterpret_cast这种没有安全性保证的工作。
类似ia & obj 这种操作如果失败,会抛出异常

程序代码如下
CMakeLists.txt

cmake_minimum_required(VERSION 2.6)
project(chat_room)

add_definitions(-std=c++14)


find_package(Boost REQUIRED COMPONENTS 
    system
    filesystem
    serialization
    )

include_directories(${Boost_INCLUDE_DIRS})

file( GLOB APP_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp)
foreach( sourcefile ${APP_SOURCES} )
    file(RELATIVE_PATH filename ${CMAKE_CURRENT_SOURCE_DIR} ${sourcefile})
    if( NOT ${filename} MATCHES "parse_msg.cpp" )
        string(REPLACE ".cpp" "" file ${filename})
        add_executable(${file} ${sourcefile} "parse_msg.cpp")
        target_link_libraries(${file} ${Boost_LIBRARIES})
        target_link_libraries(${file} pthread)
    endif( NOT ${filename} MATCHES "struct_header.cpp" )
endforeach( sourcefile ${APP_SOURCES} )

serialization_object.h

#ifndef _SERIALIZATION_OBJECT_H_
#define _SERIALIZATION_OBJECT_H_

#include 
#include 

class SBindName {
    private:
        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 {
    private: 
        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 {

    public:
        SRoomInfo(std::string name, std::string info): m_bind(std::move(name)), m_chat(std::move(info)) {}
        SRoomInfo() {}

        const std::string& name() const { return m_bind.bindName(); }
        const std::string& information() const { return m_chat.chatInformation(); }
    private:
        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;
};

#endif

parse_msg.h

#ifndef _PARSE_MSG_H_
#define _PARSE_MSG_H_
#include "serilization_object.h"

#include 
#include 
#include 
#include 
#include 


struct Header {
    int bodySize; // 包体大小 
    int type; // 消息类型
};

enum MessageType {
    MT_BIND_NAME = 1,
    MT_CHAT_INFO = 2,
    MT_ROOM_INFO = 3,
};

bool parseMessage(const std::string& input, int* type, std::string& outbuffer);
#endif

parse_msg.cpp

#include "parse_msg.h"


template  
std::string serialize(const T& obj) {
    std::stringstream ss;
    boost::archive::text_oarchive oa(ss);
    oa & obj;
    return ss.str();
}

// 消息解析函数
// input 输入的消息字符串
// type 传出的消息类型指针
// outbuffer 输出的用于发送的消息内容字符串
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 command = input.substr(0, pos);
    // Bind姓名消息
    if(command == "BindName") {
        std::string name = input.substr(pos+1);
        if(name.size()>32) {
            std::cerr << "姓名的长度大于32个字节!" <<  std::endl;
            return false;
        }
        
        if(type) {
            *type = MT_BIND_NAME;
        }

        outbuffer = serialize(SBindName(std::move(name)));
        return true;
        // 聊天消息
    }else if(command == "Chat") {
        std::string chat = input.substr(pos+1);
        if(chat.size() > 256) {
            std::cerr << "消息的长度大于256个字节!" << std::endl;
            return false;
        }

        outbuffer = serialize(SChatInfo(std::move(chat)));

        if(type) {
            *type = MT_CHAT_INFO;
        }

        return true;
    }   
    
    // 不支持的消息类型,返回false
    return false;
}

chat_message.h

#ifndef _CHAT_MESSAGE_H_
#define _CHAT_MESSAGE_H_

#include "parse_msg.h"

#include 
#include 
#include 
#include 
#include 

class chat_message {
    public:
        // Header的大小变为8个字节,使用sizeof关键字进行计算
        enum { header_length = sizeof(Header) };
        enum { max_body_length = 512 };

        chat_message() {}
        
        // 这里返回的data不可以修改
        const char* data() const { return data_; }
        char* data() { return data_; }
        
        // 计算总长度时,需要通过m_header获取到bodySize
        std::size_t length() const { return header_length + m_header.bodySize; }
        
        // body为 data_往后面移动 head_length个字节
        const char* body() const { return data_ + header_length; }
        char* body() { return  data_ + header_length; }
        
        int type() const { return m_header.type; }


        std::size_t body_length() const { return m_header.bodySize; }

        void setMessage(int messageType, const void* buffer, size_t bufferSize) {
            // 确认body大小未超过限制
            assert(bufferSize < max_body_length);

            m_header.bodySize = bufferSize;
            m_header.type = messageType;
            std::memcpy(body(), buffer, bufferSize);
            std::memcpy(data(), &m_header, sizeof(m_header));
        }

        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 << " header type:" << m_header.type  << std::endl;
                return false;
            }

            return true;
        }
        
    private:
        char data_[header_length+max_body_length];
        Header m_header;
};
#endif

client.cpp

#include "chat_message.h"
#include 
#include 
#include 
#include 

#include 

using boost::asio::ip::tcp;

using chat_message_queue = std::deque;

class chat_client {
    public:
        chat_client(boost::asio::io_service& io_service,
                    tcp::resolver::iterator endpoint_iterator
                ): io_service_(io_service), socket_(io_service) {
            do_connect(endpoint_iterator);
        }

        void write(const chat_message& msg) {
            // write是由主线程往子线程写东西
            // 所以需要使用post提交到子线程运行
            // 使得所有io操作都由io_service的子线程掌握
            io_service_.post(
                    [this, msg] () {

                        bool write_in_progress = !write_msgs_.empty();
                        write_msgs_.push_back(msg);
                        if(!write_in_progress) {
                            do_write();
                        }
                    }
                    );
        } 

        
        void close() {
            io_service_.post(
                    [this] () {
                        socket_.close();
                    }
                    );
        }
    private:
      
        void do_connect(tcp::resolver::iterator endpoint_iterator) {
            boost::asio::async_connect(
                        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(
                        socket_,
                        boost::asio::buffer(read_msg_.data(), chat_message::header_length),
                        [this] (boost::system::error_code ec, std::size_t length) {
                            if(!ec && read_msg_.decode_header()) {
                                // 如果没有错误,并且Decode_header成功,成功读取到body_length
                                do_read_body();
                            }else {
                                // 读取失败时关闭与服务端的连接,退出事件循环
                                socket_.close();
                            }
                        }
                    );
        }

        template  
        T toObject() {
            T obj;
            std::stringstream ss(std::string(read_msg_.body(), read_msg_.body() + read_msg_.body_length()));
            boost::archive::text_iarchive ia(ss);
            ia & obj;
            return obj;
        }

        void do_read_body() {
            boost::asio::async_read(
                        socket_,
                        boost::asio::buffer(read_msg_.body(), read_msg_.body_length()),
                        [this] (boost::system::error_code ec, std::size_t length) {
                            if(!ec) {
                                // 校验一下消息长度和消息类型,
                                // 证明确实发过来的是RomInformation消息
                                if(read_msg_.type() == MT_ROOM_INFO) {
                                    auto info = toObject();
                                    std::cout << "client ";
                                    std::cout << info.name();
                                    std::cout << " says: ";
                                    std::cout << info.information();
                                    std::cout << "\n";
                                
                                }
                                // 调用do_read_header函数串联起事件链,接着读
                                do_read_header();
                            }else {
                                socket_.close();
                            }
                            
                        }
                    );
        }
        
        // 向服务端真正发送消息的函数
        void do_write() {
            boost::asio::async_write(
                        socket_,
                        boost::asio::buffer(
                            write_msgs_.front().data(),
                            write_msgs_.front().length()
                            ),
                        [this] (boost::system::error_code ec, std::size_t length) {
                            if(!ec) {
                                // 一直写直到写完
                                write_msgs_.pop_front();
                                if(!write_msgs_.empty()) {
                                    do_write();
                                }
                            }else {
                                socket_.close();
                            }
                        }
                    );
        }

        // 注意使用了引用类型,
        // io_service对象的生命周期必须要大于chat_client对象的生命周期
        // 否则会出现引用失效,导致异常
        boost::asio::io_service& io_service_;
        tcp::socket socket_;
        chat_message read_msg_;
        chat_message_queue write_msgs_;
};


int main(int argc, char* argv[]) {
    try {
        if(argc != 3) {
            std::cerr << "Usage: chat_client  " << std::endl;
            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(); });
        char line[chat_message::max_body_length + 1];

        // Ctrl + D 正常退出一个应用程序
        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(parseMessage(input, &type, output)) {
                msg.setMessage(type, output.data(), output.size());
                c.write(msg);
            }
        }

        c.close();
        t.join();

    }catch(std::exception& ex) {
        std::cerr << "Exception: " << ex.what() << std::endl;
    }

    return 0;
}

server.cpp

#include "chat_message.h"

#include 

#include 
#include 
#include 
#include 
#include 
#include 

#include 

using boost::asio::ip::tcp;

using chat_message_queue = std::deque;

class chat_session;
using chat_session_ptr = std::shared_ptr;

// 聊天室类的声明
class chat_room {
    public:
        void join(chat_session_ptr);
        void leave(chat_session_ptr);
        void deliver(const chat_message&);
    private:
        std::set participants_;
        enum { max_recent_msgs = 100 };
        chat_message_queue recent_msgs_;
};

class chat_session: public std::enable_shared_from_this {
    public:
        chat_session(tcp::socket socket, chat_room& room): socket_(std::move(socket)), room_(room) {}

        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);            

            // 为了保护do_write线程里面的deque,避免两个线程同时写
            if(!write_in_progress) {
                do_write();
            }
        }
    private:
        // 读取消息头
        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) {
                            // 头部解析成功,获取到body_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) {
                        // 如果读取消息成功,没有error
                        if(!ec) {
                            // room_的deliver msg,会先更新recent_message queue,
                            // 然后调用各;个Session的Deliver message
                            // 将消息发给对应的client 
                            // room_.deliver(read_msg_);
                            handleMessage();
                            
                            // 接着读头,形成事件循环
                            do_read_header();
                        }else {
                            room_.leave(shared_from_this());
                        }
                    }
                );
        }
        
        template  
        T toObject() {
            T obj;
            std::stringstream ss(std::string(read_msg_.body(), read_msg_.body() + read_msg_.body_length()));
            boost::archive::text_iarchive ia(ss);
            ia & obj;
            return obj;
        }


    
        // 处理接收到的客户端的消息的函数
        void handleMessage() {
            if(read_msg_.type() == MT_BIND_NAME) {
                auto bindName = toObject();
                m_name = bindName.bindName();
            } else if(read_msg_.type() == MT_CHAT_INFO) {
                auto chat = toObject();
                m_chatInformation = chat.chatInformation();

                auto rinfo = buildRoomInfo();
                chat_message msg;
                msg.setMessage(MT_ROOM_INFO, rinfo);
                room_.deliver(msg);
            } else {
                //不可用消息,啥也不做
            }
        }
        
        // 构建一个RoomInformation信息
        std::string buildRoomInfo() const {
            SRoomInfo roomInfo(m_name, m_chatInformation);
            std::stringstream ss;
            boost::archive::text_oarchive oa(ss);
            oa & roomInfo;
            return ss.str();
        }

        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());
                            }
                        }
                    );
        }

        tcp::socket socket_;
        // room的生命周期必须长于session的生命周期,
        // 否则会因为持有无效的引用而翻车
        chat_room& room_;
        chat_message read_msg_;
        chat_message_queue write_msgs_;
        std::string m_name; // 客户端姓名
        std::string m_chatInformation; // 客户端当前的消息
};


void chat_room::join(chat_session_ptr participant) {
    participants_.insert(participant);
    
    // 给新加入者广播一遍历史消息
    for(const auto& msg: recent_msgs_) {
        participant->deliver(msg);
    }
}

void chat_room::leave(chat_session_ptr participant) {
    participants_.erase(participant);
}

// 消息分发函数
void chat_room::deliver(const chat_message& msg) {
    recent_msgs_.push_back(msg);
    // recent_msgs_调整到最大值
    while(recent_msgs_.size() > max_recent_msgs) {
        recent_msgs_.pop_front();
    }

    // 给每个群聊参与者群发消息
    for(auto & participant: participants_) {
        participant->deliver(msg);
    }
}


class chat_server {
    public:
        chat_server(boost::asio::io_service& io_service, 
                    const tcp::endpoint& endpoint): acceptor_(io_service, endpoint), 
                                                    socket_(io_service){
                                                        do_accept();
                                                    }
        
        // 接收来自客户端的连接的函数
        void do_accept() {
            acceptor_.async_accept(
                        socket_, 
                        [this] (boost::system::error_code ec) {
                            // 如果接收连接成功,没有错误
                            if(!ec) {
                                auto session = std::make_shared(std::move(socket_),
                                        room_
                                    );

                                session->start();
                            } 

                            // 无论成功或失败,都继续接收连接
                            do_accept();
                        }
                    );
        }
    private:
        tcp::acceptor acceptor_;
        tcp::socket socket_;
        chat_room room_;
};


int main(int argc, char* argv[]) {

    try {
        if(argc < 2) {
            std::cerr << "Usage: chat_server  [ ...]" << std::endl;
            return 1;
        }
        
        boost::asio::io_service io_service;

        std::list servers;
        
        for(int i=1; i

程序输出如下


图片.png

图片.png

你可能感兴趣的:(使用boost::archive库序列化改进聊天程序)