为结构提升套接字 read_until

boost sockets read_until for structs

我已经成功开始使用 C++ 中的套接字,并在 python 客户端中连接到它。我首先发送纯字符串并在遇到分隔符时停止 C++ Boost(在我的例子中我使用

// C++ boost Socket Server
std::string read_socket_command(tcp::socket & socket) {
   boost::asio::streambuf buf;
   boost::asio::read_until( socket, buf, "\n" );
   std::string data = boost::asio::buffer_cast<std::string*>(buf.data());
   return data;
}

http://think-async.com/Asio/boost_asio_1_12_1/doc/html/boost_asio/overview/core/line_based.html

我的问题是,现在在 Python 客户端中,我想将数据作为结构打包发送。但是如何让 C++ 代码停止读取数据呢?

# Python Client
import struct

DATA_NAME_String = "string int int int long long int int int"
DATA_FORMAT_STRING = "25s I I I I I I I I"


def pack_data(msg):
    debug_print("Packing a message...")
    if type(msg) is SomeCustomType:
        data = ("hi", 22, 1, 4, 457, 42342, 0, 1)
    packer = struct.Struct(DATA_FORMAT_STRING)
    packed_data = packer.pack(*data)
    return packed_data

在您的打包数据中,让前 4 个字节 (uint32_t) 指示有效载荷的字节数。简而言之,在发送二进制数据时,您应该预先向对方发送大小。 read_until 对文本协议有效,但对于二进制数据,您可能必须使用 read.