如何使用boost::asio发送原始二进制数据
How to send raw binary data using boost::asio
我正在使用boost::asio
编写TCP客户端。我想发送一个浮点数的二进制数组。boost是否提供了一种将数据转换为二进制表示的好方法,以便将其放置在boost::数组或其他东西中?
我过去使用过Qt QDataStream
,它工作得很好;我相信boost有类似的东西?
#include <boost/asio.hpp>
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include <iostream>
int
main( unsigned argc, char** argv )
{
if ( argc < 3 ) {
std::cerr << "usage: " << argv[0] << " host port" << std::endl;
exit( EXIT_FAILURE );
}
boost::array<float, 5> foo = {1.0, 2.0, 3.0, 4.0, 5.0};
BOOST_FOREACH( const float i, foo ) {
std::cout << i << std::endl;
}
boost::asio::io_service ios;
boost::asio::ip::tcp::socket socket( ios );
socket.connect(
boost::asio::ip::tcp::endpoint(
boost::asio::ip::address::from_string( argv[1] ),
boost::lexical_cast<unsigned>( argv[2] )
)
);
const size_t bytes = boost::asio::write(
socket,
boost::asio::buffer( foo )
);
std::cout << "sent " << bytes << " bytes" << std::endl;
}
编译bash-3.2$ g++ -I /opt/local/include -L/opt/local/lib -lboost_system -Wl,-rpath,/opt/local/lib array.cc
运行bash-3.2$ ./a.out 127.0.0.1 1234
1
2
3
4
5
sent 20 bytes
bash-3.2$
服务器bash-3.2$ nc -l 1234 | hexdump -b
0000000 000 000 200 077 000 000 000 100 000 000 100 100 000 000 200 100
0000010 000 000 240 100
0000014
bash-3.2$
您可以通过ASIO发送任何类型的数据,就像您可以将任何类型的数据写入文件一样:
T x; // anything
const char * px = reinterpret_cast<const char*>(&x); // no type punning, cast-to-char is allowed
boost::asio::async_write(my_socket, boost::asio::buffer(px, sizeof(T)), ...
或者直接写入文件:
std::ofstream f("data.bin");
f.write(px, sizeof(T));
将任何变量强制转换为char*
是标准明确允许的,大概正是因为您必须能够将二进制数据序列化为文件和套接字等
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 有根的二进制搜索树.保留与其父级的链接
- 多态二进制函数
- 正在读取二进制文件(is_open)
- visual在c++中将十进制数转换为二进制数
- C++十进制到二进制,如何转换
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 二进制搜索树叶数问题
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 返回二进制数据的通用方式,而无需原始指针
- 原始二进制树删除与复制问题(改进解释)
- 将原始声音转换为二进制标头
- OpenCV:如何使用阈值正确分割图像/使用二进制图像对原始图像进行分割
- 编译C++二进制文件是否存储原始源代码
- Qt/C++-转换原始二进制数据并将其显示为图像(即QImage)
- 如何使用boost::asio发送原始二进制数据
- 将一个文件编码为1/0二进制文件,并在c++中重建原始文件
- C++ ifstream,ofstream:原始read()/write()调用和以二进制模式打开文件有什么区别?
- 如何在Visual Studio中添加原始二进制数据到源代码中
- 二进制文件在c++中,改变音频文件上的原始数据的内容