Boost Asio,聊天示例:我如何手动在消息正文中写入?[聊天消息.hpp]

Boost Asio, chat example: How do I manually write in the body of the message? [chat_message.hpp]

本文关键字:聊天 消息 正文 hpp 何手动 Asio Boost      更新时间:2023-10-16

我正在学习Boost Asio教程中的"聊天示例"。由于我对Boost Asio没有太多经验,我正在使用聊天示例实现我自己的客户端-服务器应用程序,并根据我的需要对其进行修改。

现在我正在定义一个Protocol.hpp文件,其中包含网络协议的关键字。例如:

协议.hpp

#ifndef PROTOCOL_HPP
#define PROTOCOL_HPP
#include <iostream>
extern const char ACK;
#endif

协议.cpp

#include "Protocol.hpp"
const char ACK = "1";

如果您查看"chat_message.hpp"类,您会发现以下内容:

  const char* data() const
  {
    return data_;
  }
  char* data()
  {
    return data_;
  }

我尝试过以下几种:

std::sprintf(write_msgs_.data(), ACK, 2);

除了尝试像这样直接分配所需的代码之外——然而,我想我正在获得const函数——:

write_msgs_.data() = ACK;

我曾想过使用string类,然后以某种方式将其转换为char,以便将其复制到write_msgs_.data()中,甚至用循环添加每个字符。我对C++还比较陌生,似乎没有找到一个好的解决方案有什么合适的方法吗

事先非常感谢。

我找到了它。我应该检查一下示例应用程序是如何做到的,它只是使用了cstring库中的memcpy。因此,任何和我有同样问题的人都应该使用以下方法:

chat_client.cpp文件的main

char line[chat_message::max_body_length + 1];
while (std::cin.getline(line, chat_message::max_body_length + 1))
{
  using namespace std; // For strlen and memcpy.
  chat_message msg;
  msg.body_length(strlen(line));
  memcpy(msg.body(), line, msg.body_length());
  msg.encode_header();
  c.write(msg);
}

正如您所看到的,有一个char line变量将保存书面文本。之后,memcpy用于将该行复制到消息的正文中。