I am following the " chat example " from Boost Asio's tutorials. As I don't have much experience with Boost Asio, I am implementing my own client server application using the chat example and modifying it according to my needs.
Now I am defining a Protocol.hpp file, which contains keywords for the network protocol. For example:
Protocol.hpp
#ifndef PROTOCOL_HPP
#define PROTOCOL_HPP
#include <iostream>
extern const char ACK;
#endif
Protocol.cpp
#include "Protocol.hpp"
const char ACK = "1";
If you take a look at the "chat_message.hpp" class, you will find the following:
const char* data() const
{
return data_;
}
char* data()
{
return data_;
}
I have tried the following:
std::sprintf(write_msgs_.data(), ACK, 2);
As well as trying to assign directly the desired code like this —however I guess that I am obtaining the const
function—:
write_msgs_.data() = ACK;
I have thought of using the string
class and then somehow convert it to char
, in order to copy it in the write_msgs_.data()
, or even adding every character with a loop. I am relatively new to C++, and I don't seem to find a good solution for this. Is there any proper way of doing this?
Thank you very much in advance.
I found it. I should have checked how the example application does it, and it simply uses memcpy
from the cstring
library. Therefore, anyone having the same problem as me should use the following:
main
of the chat_client.cpp
file:
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);
}
As you can see there is a char line
variable that will hold the written text. After this, memcpy
is used to copy the line to the body of the message.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.