Boost Asio,聊天示例:我如何手动在消息正文中写入?[聊天消息.hpp]
Boost Asio, chat example: How do I manually write in the body of the message? [chat_message.hpp]
我正在学习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
用于将该行复制到消息的正文中。
相关文章:
- boost::进程间消息队列引发错误
- 在线编译器中的分段C++没有打印消息
- C++错误消息*成员参考.**初学者*
- 在createdialog创建的窗口中捕获用于编辑控件的OnMouseMove消息
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 如何通过参数抛出错误消息
- 从服务器传输到客户端的消息不会出现
- ROS2 动态消息模板
- C++秘密消息学校作业
- glad 导致 glfwSwapBuffers 返回错误消息
- C++入门 5 版:类消息和文件夹
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- 如何处理从一个对象传递到另一个在C++中具有公共抽象类的对象的消息
- 如何接受 [ENTER] 键作为无效输入并发送错误消息
- boost/asio:非常简单的聊天服务器无法访问收到的消息
- C++ HexChat 发送消息获取聊天
- Boost Asio,聊天示例:我如何手动在消息正文中写入?[聊天消息.hpp]
- 如何制作同步聊天程序以同步发送和接收消息
- 聊天程序在c++中返回无限消息
- xmpp向face book聊天api进行身份验证,并且总是收到失败消息