我想使用 boost::asio::ip::tcp::socket 的方法“read_some()”来填充一个表示为 char* 的缓冲区。
到目前为止,这是我的方法实现:
template<class charType>
int receive_some(charType* buffer, int size)
{
int total_received = 0;
boost::array<charType, size> buf;
while (1)
{
int received = 0;
boost::system::error_code error;
received = _socket.read_some(boost::asio::buffer(buf), error);
if (error == boost::asio::error::eof)
{
break;
}
std::cout.write(buf.data(), received);
total_received += received;
}
return total_received;
}
我的问题是我不知道如何将我的 charType* 缓冲区转换为 boost::array buf。在过程结束时迭代我的 boost::array 的元素似乎很昂贵,只是为了填充缓冲区对象...
有什么想法吗?
最佳答案
template<class charType>
int receive_some(charType* buffer, int size)
{
int total_received = 0;
while (1)
{
int received = 0;
boost::system::error_code error;
received = _socket.read_some(boost::asio::buffer(buffer, size), error);
if (error == boost::asio::error::eof)
{
break;
}
std::cout.write(buffer, received);
total_received += received;
}
return total_received;
}
boost::asio::buffer函数有很多重载以允许从不同类型的源创建 asio 缓冲区。
值得注意的是,size
必须是要读入 buffer
的字节数,而不是 charType
的数量。
额外提示:正如评论所指出的那样,该模板是可疑的,您可以用它做的最好的事情是直接写入宽字符串,但这可能比在 read_some
函数中更好(实际上它甚至可能更好),在网络功能中你处理字节而不是字符所以你最好采用简单的 char*
甚至 void*
作为类型buffer
参数。
关于c++ - 将 char* 转换为 boost::array 以供套接字使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26670826/