如何使用boost :: asio发送原始二进制数据

时间:2011-07-28 21:39:52

标签: c++ boost-asio

我正在使用boost::asio编写TCP客户端。我想以二进制表示形式发送一个浮点数组。 boost是否提供了将数据转换为二进制表示形式以将其放置在boost :: array或其他内容中的好方法?

我过去使用过Qt QDataStream并且效果很好;我相信提升有相当的东西吗?

2 个答案:

答案 0 :(得分:3)

#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$

答案 1 :(得分: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*,这可能正是因为您必须能够将二进制数据序列化为文件和套接字等。

相关问题