简体   繁体   English

为什么boost :: asio :: ip :: tcp :: iostream解析输入?

[英]Why boost::asio::ip::tcp::iostream parses input?

I try to use the iostream class from boost ASIO to read binary data from a TCP socket. 我尝试使用boost ASIO中的iostream类从TCP套接字读取二进制数据。 I use the standard extraction operator (operator>>) to read data from the stream. 我使用标准提取运算符(operator >>)从流中读取数据。 The environment I use is Visual Studio 2010. The problem is that when I read the stream it seems that the stream tries to parse the binary data as a string. 我使用的环境是Visual Studio2010。问题是,当我读取流时,似乎流试图将二进制数据解析为字符串。 At least this is what I have seens as I have debugged into the code. 至少这是我调试代码后所看到的。

Is there a way that I could use the iostream to read it as a binary stream and not as a string stream? 有没有一种方法可以使用iostream将其读取为二进制流而不是字符串流?

boost::asio::io_service dataServer;

boost::asio::ip::tcp::endpoint dataServerEndpoint(boost::asio::ip::tcp::v4(), dataServerPort);
boost::asio::ip::tcp::acceptor acceptor(dataServer, dataServerEndpoint);

boost::asio::ip::tcp::iostream dataServerStream;
acceptor.accept(*dataServerStream.rdbuf());

try
{
    vector<char> lineBuffer;

    while (!dataServerStream.eof())
    {

        bool eof = dataServerStream.eof();
        bool bad = dataServerStream.bad();
        bool fail = dataServerStream.fail();
        bool good = dataServerStream.good();

        uint64_t magic;
        dataServerStream >> magic;

So instead of just taking 8 bytes from stream and move it into the "magic" variable, it tries to parse the stream to get a valid stringified number. 因此,它不仅尝试从流中获取8个字节并将其移动到“ magic”变量中,还尝试解析流以获取有效的字符串化数字。 This of course fails and the fail bit will be set. 这当然会失败,并且会设置失败位。

The input operator >> is expecting the input to be text, that is then converted to the correct data-type. 输入运算符>>期望输入为文本,然后将其转换为正确的数据类型。 As you can expect this will not work well with binary data. 如您所料,这不适用于二进制数据。

You should be using read instead: 您应该使用read代替:

uint64_t magic;
dataServerStream.read(reinterpret_cast<char*>(&magic), sizeof(magic));

You also make a very common beginner mistake, in that you loop while (!eof) . 您还会犯一个很常见的初学者错误,因为您while (!eof)循环。 This will not work as the eof flag is not set until after you try an input operation. 因为这将无法正常工作eof标志没有设置,直到您尝试输入操作之后 This means you will iterate once to many. 这意味着您将迭代一次。

Instead do eg 相反,例如

uint64_t magic;
while (dataServerStream.read(reinterpret_cast<char*>(&magic), sizeof(magic)))
{
    // Read the rest
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM