boost::asio TCP socket聊天室扩展(通过POD(Plain old data structure)结构体,以内存的字节流作为传递信息)

//
//  structHeader.hpp
//  ServerOfChat
//
//  Created by ma qianli on 2020/3/11.
//  Copyright © 2020 qianli. All rights reserved.
//

#ifndef structHeader_hpp
#define structHeader_hpp

#include <stdio.h>
#include <string>

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


#endif /* structHeader_hpp */


//
//  structHeader.cpp
//  ServerOfChat
//
//  Created by ma qianli on 2020/3/11.
//  Copyright © 2020 qianli. All rights reserved.
//

#include <cstring>
#include "structHeader.hpp"

//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;
}

/



#ifndef CHAT_MESSAGE_HPP
#define CHAT_MESSAGE_HPP

#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>

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

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"

///
//下面是客户端main.cpp

#include <cstdlib>
#include <deque>
#include <iostream>
#include <thread>
#include <boost/asio.hpp>
                                                                        
#include "chat_message.hpp"
                     
using boost::asio::ip::tcp;
                     
using chat_message_queue = std::deque<chat_message>;
                     
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.body_length() == sizeof(RoomInformation) && m_read_msg.type() == 3) {
                    const RoomInformation *info = (RoomInformation*)m_read_msg.body();
                    std::cout << "client: '";
                    assert(info->name.nameLen <= sizeof(info->name.nameLen));
                    std::cout.write(info->name.name, info->name.nameLen);
                    std::cout << "' says '";
                    assert(info->chat.infolen <= sizeof(info->chat.information));
                    std::cout.write(info->chat.information, info->chat.infolen);
                    std::cout << "'\n";
                }
                
                //继续读取下一条信息的头
                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 <host> <port>\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 (parseMessage(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;
}

///
//下面是服务端main.cpp


#include <deque>
#include <iostream>
#include <list>
#include <set>
#include <memory>
#include <boost/asio.hpp>
#include "chat_message.hpp"

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

//----------------------------------------------------------------------

using chat_message_queue = std::deque<chat_message>;

//----------------------------------------------------------------------

class chat_participant
{
public:
  virtual ~chat_participant() {}
  virtual void deliver(const chat_message& msg) = 0;
};

using chat_participant_ptr = std::shared_ptr<chat_participant> ;

//----------------------------------------------------------------------

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<chat_participant_ptr> participants_;
  enum { max_recent_msgs = 100 };
  chat_message_queue recent_msgs_;
};

//----------------------------------------------------------------------

class chat_session
  : public chat_participant,
    public std::enable_shared_from_this<chat_session>
{
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());
//    boost::asio::async_read(socket_,
//        boost::asio::buffer(read_msg_.data(), chat_message::header_length),
//        boost::bind(
//          &chat_session::handle_read_header, shared_from_this(),
//          boost::asio::placeholders::error));
      
      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)
    {
//      boost::asio::async_write(socket_,
//          boost::asio::buffer(write_msgs_.front().data(),
//            write_msgs_.front().length()),
//          boost::bind(&chat_session::handle_write, shared_from_this(),
//            boost::asio::placeholders::error));
        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 handle_read_header(const boost::system::error_code& error)
//  {
//    if (!error && read_msg_.decode_header())
//    {
//      boost::asio::async_read(socket_,
//          boost::asio::buffer(read_msg_.body(), read_msg_.body_length()),
//          boost::bind(&chat_session::handle_read_body, shared_from_this(),
//            boost::asio::placeholders::error));
//    }
//    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());
            }
        });
    }
    
    void handleMessage(){
        if (read_msg_.type() == 1) {
            const BindName *bind = (BindName*)read_msg_.body();
            m_name.assign(bind->name, bind->name + bind->nameLen);
        }else if (read_msg_.type() == 2){
            const ChatInformation *chat = (ChatInformation*)read_msg_.body();
            m_chatInformation.assign(chat->information, chat->information + chat->infolen);
            auto rinfo = buildRoomInfo();
            chat_message msg;
            msg.setMessage(3, &rinfo, sizeof(rinfo));
            room_.deliver(msg);
        }
    }
    
    RoomInformation buildRoomInfo(){
        RoomInformation info;
        info.name.nameLen = (int)m_name.size();
        std::memcpy(info.name.name, m_name.data(), m_name.size());
        info.chat.infolen = (int)m_chatInformation.size();
        std::memcpy(info.chat.information, m_chatInformation.data(), m_chatInformation.size());
        return  info;
    }
    
//  void handle_read_body(const boost::system::error_code& error)
//  {
//    if (!error)
//    {
//      room_.deliver(read_msg_);
//      boost::asio::async_read(socket_,
//          boost::asio::buffer(read_msg_.data(), chat_message::header_length),
//          boost::bind(&chat_session::handle_read_header, shared_from_this(),
//            boost::asio::placeholders::error));
//    }
//    else
//    {
//      room_.leave(shared_from_this());
//    }
//  }
//
    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());
            }
        });
    }
    
//  void handle_write(const boost::system::error_code& error)
//  {
//    if (!error)
//    {
//      write_msgs_.pop_front();
//      if (!write_msgs_.empty())
//      {
//        boost::asio::async_write(socket_,
//            boost::asio::buffer(write_msgs_.front().data(),
//              write_msgs_.front().length()),
//            boost::bind(&chat_session::handle_write, shared_from_this(),
//              boost::asio::placeholders::error));
//      }
//    }
//    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> 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)
  {
//    chat_session_ptr new_session(new chat_session(io_service_, room_));
//    acceptor_.async_accept(new_session->socket(),
//        boost::bind(&chat_server::handle_accept, this, new_session,
//          boost::asio::placeholders::error));
      do_accept();
  }
    
    void do_accept(){
        acceptor_.async_accept(socket_, [this](boost::system::error_code ec){
            if (!ec) {
                std::make_shared<chat_session>(std::move(socket_), room_)->start();
            }
            
            do_accept();
        });
    }

//  void handle_accept(chat_session_ptr session,
//      const boost::system::error_code& error)
//  {
//    if (!error)
//    {
//      session->start();
//      chat_session_ptr new_session(new chat_session(io_service_, room_));
//      acceptor_.async_accept(new_session->socket(),
//          boost::bind(&chat_server::handle_accept, this, new_session,
//            boost::asio::placeholders::error));
//    }
//  }

private:
  tcp::socket socket_;
  tcp::acceptor acceptor_;
  chat_room room_;
};

typedef boost::shared_ptr<chat_server> chat_server_ptr;
typedef std::list<chat_server_ptr> chat_server_list;

//----------------------------------------------------------------------

int main(int argc, char* argv[])
{
  try
  {
    if (argc < 2)
    {
      std::cerr << "Usage: chat_server <port> [<port> ...]\n";
      return 1;
    }

    boost::asio::io_service io_service;
      
      std::list<chat_server*> 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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值