简单的聊天室服务器 基于Boost asio(3)--消息协议设计

客户端如果要和服务器做交流,那么肯定需要一套双方都认可的交流方式。比如说我们日常都说普通话,忽然来一个阿拉斯加“”汪汪汪“”的和你说话,这时候,就算你换成英语也没用。必须有一套双方都遵循的交流规则。 也就是 消息协议。
话不多说 上代码

class chat_message {
public:
enum { header_length = 4 };
enum { max_body_length = 512 };
// 包头长度=4 包体长度=512

char *body() { return data_ + header_length; }
//报文指针+包头长度=包体位置

//设置包体长度 如果超过512 裁掉超过部分

void body_length(std::size_t new_length) { body_length_ = new_length; if (body_length_ > max_body_length) body_length_ = max_body_length; }
//data中的数据放入header,分割包头内容,而包头长度+1是为了保存字符串最后一位的‘\0’
如果包长超过512 那么置空

  bool decode_header() {
		// "5212"
    char header[header_length + 1] = "";
    std::strncat(header, data_, header_length);
    body_length_ = std::atoi(header);
    if (body_length_ > max_body_length) {
      body_length_ = 0;

//包体长度的信息放入包头

 void encode_header() {
    char header[header_length + 1] = "";
    std::sprintf(header, "%4d", static_cast<int>(body_length_));
    std::memcpy(data_, header, header_length);
  }
private:
  char data_[header_length + max_body_length];
  std::size_t body_length_;//真实包体长度
};

通过对消息协议的解析,我们知道包的结构是包头+包体。
而TCP是一个面向字节流的稳定连接服务。因此字节式的包结构,在TCP中传递更加的符合设计。下次我们来解析服务器端对于消息的收发控制。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果你想在 C++ 中使用 MySQL,并且不依赖于 Boost 库,你可以考虑使用第三方库 mysql-async。mysql-async 提供了一个基于非阻塞的异步操作接口,使用 asio 库进行底层网络通信。 以下是一个简单的示例代码,展示了如何使用 mysql-async 连接到 MySQL 数据库并执行查询操作: ```cpp #include <iostream> #include <mysql_async/mysql_async.h> int main() { boost::asio::io_service io_service; // 创建 MySQL 连接对象 mysql_async::connection conn(io_service); // 异步连接到数据库 conn.async_connect("tcp://127.0.0.1:3306", "user", "password", [](const boost::system::error_code& ec) { if (!ec) { std::cout << "Connected to MySQL server" << std::endl; // 异步执行查询操作 conn.async_query("SELECT * FROM table_name", [](const boost::system::error_code& ec, mysql_async::resultset_ref result) { if (!ec) { std::cout << "Query executed successfully" << std::endl; // 遍历结果集 while (result->next()) { std::cout << "Column 1: " << result->get_string(0) << std::endl; std::cout << "Column 2: " << result->get_string(1) << std::endl; // ... } } else { std::cout << "Error executing query: " << ec.message() << std::endl; } }); } else { std::cout << "Error connecting to MySQL server: " << ec.message() << std::endl; } }); // 运行异步操作 io_service.run(); return 0; } ``` 请注意,你需要在代码中包含 `mysql_async/mysql_async.h` 头文件,并将 mysql-async 库链接到你的项目中。 这只是一个简单的示例,你可以根据 mysql-async 的文档和示例进行更复杂的操作,如插入、更新、删除等。你可以在 mysql-async 的 GitHub 仓库中找到更多的信息和用法示例:https://github.com/mysql-net/mysql-async

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值