繁体   English   中英

boost :: asio客户端连接停止接收数据

[英]boost::asio client connection stops receiving datas

我真的很愿意为我的C ++应用程序学习boost :: asio。 因此,我从一个“简单”的客户端应用程序开始,该应用程序在笔记本电脑上编译并运行。 这个想法真的很简单。 客户端启动与服务器的连接,并每2秒询问一次答案。 我有可能触发服务器的状态(比如说警报信号)。 作为响应,当客户端尝试连接到服务器时,后者将通知服务器必须准备接收一些数据(具有一些双精度和整数值的列表)。 客户端询问列表,服务器通过连接发送想要的列表。

问题:列表未完全传送。 列表中的一大块将被发送并正确接收,但是随后我再也没有收到任何数据。

由于我将应用程序拆分为类,因此代码如下:

客户端

#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <ostream>
#include <chrono>

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/array.hpp>
#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/ip/tcp.hpp>

#ifndef __CLIENT_CLASS__
#define __CLIENT_CLASS__

//#define DEBUG

class Client
{
    boost::asio::io_service io_service_;

    boost::asio::ip::tcp::resolver resolver_{ io_service_ };
    boost::asio::ip::tcp::socket   socket_{ io_service_ };

    boost::asio::streambuf request_;
    boost::asio::streambuf response_;

    const std::string host_server_; 
    const std::string port_; 
    const uint uiId_;            
    const long double dLon_;             
    const long double dLat_; 
    const double dHeight_;     

    const std::string useragent_ = "HTMLGET 1.0";

    enum State { STANDBY = 0x01,
                 ALARM   = 0x02,
                 WPL_REC = 0x04 };

    State state_ = STANDBY;

    std::chrono::milliseconds server_response_delay_  = std::chrono::milliseconds( 2000 ); // SERVER_RESPONSE_DELAY 
    uint uiError_ = 0;

    bool bAlarmFlag_;
    unsigned int uiRequestCounter_;

    std::chrono::high_resolution_clock::time_point begin_time_;

    public:
        explicit Client( const std::string &address, const std::string &port, uint id,
                         long double start_longitude, long double start_latitude,
                         double start_height );
        virtual ~Client();

        void run( void );

        std::chrono::milliseconds getServerResponseDelay( void ) const;
        void setServerResponseDelay( std::chrono::milliseconds milliseconds );


    private:
        void buildQuery( void );
        void handleResolve( const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator it );
        void handleConnect( const boost::system::error_code &ec );
        void handleWriteRequest( const boost::system::error_code &ec );
        void handleReadStatusLine( const boost::system::error_code &ec );
        void handleMessage( const boost::system::error_code &error_msg );
        void readContent( const boost::system::error_code &error_msg );
        void build_wpl_query( void );
        std::string build_ok_answer( void );
        std::string build_alarm_answer( void );
        std::string build_wpl_answer( void );
};

#endif

我的client.cpp 我在有问题的地方发表了一行评论。

#include "client.h"

Client::Client( const std::string &address, const std::string &port, uint id,
                         long double start_longitude, long double start_latitude,
                         double start_height ) : host_server_( address ), port_( port ),
                         uiId_(id), dLon_( start_longitude ), dLat_( start_latitude ), dHeight_( start_height )
{

    std::cout << "Constructor of the class \"Client\" called" << std::endl;

    bAlarmFlag_       = false;
    uiRequestCounter_ = 1;

    begin_time_ = std::chrono::high_resolution_clock::now();

}

Client::~Client()
{
    std::cout << "Destructor of the class \"Client\" called" << std::endl; 
}

void Client::run( void )
{
    if( std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::high_resolution_clock::now() - begin_time_ ) > server_response_delay_ ) 
    {
        begin_time_ = std::chrono::high_resolution_clock::now();

        boost::asio::ip::tcp::resolver::query local_query( host_server_, port_ );

        resolver_.async_resolve( local_query, boost::bind( &Client::handleResolve, this, boost::asio::placeholders::error, boost::asio::placeholders::iterator ) );

        size_t service_status = io_service_.run();

        std::cout << "IO Service status: " << service_status << std::endl << std::endl;

        io_service_.reset();
    }
}

void Client::handleResolve( const boost::system::error_code &error_msg, boost::asio::ip::tcp::resolver::iterator it )
{
    if( !error_msg ) {
        boost::asio::async_connect( socket_, it, boost::bind( &Client::handleConnect, this, boost::asio::placeholders::error ) );

    } else {
        std::cout << "Handle Resolv Error: " << error_msg.message() << std::endl;
    }
}

void Client::handleConnect( const boost::system::error_code &error_msg ) 
{
    if( !error_msg ) {

        std::cout << "-------------------------------------------------------------------------------";
        std::cout << std::endl << "Request Nr: " << (int)uiRequestCounter_ << std::endl;
        std::cout << "Socket created" << std::endl;

        if( !bAlarmFlag_ )
            buildQuery();
        if( bAlarmFlag_ ) {
            build_wpl_query();
            bAlarmFlag_ = false;
        }

        boost::asio::async_write( socket_, request_, boost::bind( &Client::handleWriteRequest, this, boost::asio::placeholders::error ) );

        ++uiRequestCounter_;

    } else {
        std::cout << "Handle Connect Error: " << error_msg.message() << std::endl;
    }
}

void Client::handleWriteRequest( const boost::system::error_code &error_msg )
{
    std::cout << "Waiting answer from Server..." << std::endl;

    if( !error_msg ) {

        boost::asio::async_read_until( socket_, response_, "\r\n", boost::bind( &Client::handleReadStatusLine, this, boost::asio::placeholders::error ) );      
    } else {
        std::cout << "Handle Write Request Error: " << error_msg.message() << std::endl;
    }
}

void Client::handleReadStatusLine( const boost::system::error_code &error_msg )
{
    std::string  header_string;
    unsigned int status_code;
    std::string  server_status; 

    if( !error_msg ) {
        std::istream response_stream( &response_ );
        response_stream >> header_string;
        response_stream >> status_code;
        response_stream >> server_status;


        std::cout << std::endl << header_string << "   " << status_code << "   " << server_status << std::endl;

        if( header_string.substr(0, 8) != "HTTP/1.1" ) {

            std::cout << "Not a valid message from Server" << std::endl;
            return;
        } 

        if( status_code != 200 ) {
            std::cout << "Code 200 not available from Server" << std::endl;
            return;
        }

        if( server_status != "OK" ) {

            std::cout << "Not a OK message from Server" << std::endl;
            return;
        }

        if( ( header_string.substr(0, 8) == "HTTP/1.1" ) && ( status_code == 200 ) && ( server_status == "OK" ) ) {

            std::cout << "Server OK, start retrieving data" << std::endl;

            boost::asio::async_read_until( socket_, response_, "\r\n\r\n", boost::bind( &Client::handleMessage, this, boost::asio::placeholders::error ) );

        } else {

            std::cout << "Not a valid packet from Server" << std::endl;
        }


    } else {

        std::cout << "Handle Read Status Line Error: " << error_msg.message() << std::endl;
    }
}

void Client::handleMessage( const boost::system::error_code &error_msg )
{
    if( !error_msg ) {

        std::istream response_stream( &response_ );
        std::string header_string;

        while( std::getline( response_stream, header_string ) && header_string != "\r\n" ) {

            // http://stackoverflow.com/a/30083146
/*          if( static_cast<int>( header_string.find( "Content-Length:" ) ) != -1 ) {

                std::string car = boost::regex_replace( header_string, boost::regex( "[^0-9]*([0-9]+).*" ), std::string( "\\1" ) );

                std::cout << "Content-Length: " << std::stoi( car ) << std::endl;

            }*/

            if( header_string.find( build_ok_answer() ) != std::string::npos ) {

                bAlarmFlag_ = false;
                std::cout << "I received a \033[1;32mALIVE-Signal\033[0m from the Server." << std::endl;

            } else if( header_string.find( build_alarm_answer() ) != std::string::npos ) {
                bAlarmFlag_ = true;
                std::cout << "I received a \033[1;31mALARM-Signal\033[0m from Server!" << std::endl;

            } else if( header_string.find( build_wpl_answer() ) != std::string::npos ) {

                std::cout << std::endl << "List \033[1;34mData\033[0m received." << std::endl;

/* HERE I READ A BLOCK OF THE LIST BUT NOT THE WHOLE LIST!!!! */
std::cout << &response_;

            }

        }

        boost::asio::async_read( socket_, response_, boost::asio::transfer_at_least(1), 
                                boost::bind(&Client::readContent, this, boost::asio::placeholders::error ) );

    } else {

        std::cout << "Handle Message Error: " << error_msg.message() << std::endl;
    }
}

void Client::readContent( const boost::system::error_code &error_msg )
{
    if( !error_msg ) {

        /* Read until the EOF */
        boost::asio::async_read( socket_, response_, boost::asio::transfer_at_least(1),
                                boost::bind( &Client::readContent, this, boost::asio::placeholders::error ) );

    } else if ( error_msg != boost::asio::error::eof ) {
        std::cout << "Read Content Error: " << error_msg.message() << std::endl;
    }
}

void Client::buildQuery( void )
{
    std::ostream ssRequest( &request_ );

    ssRequest << "GET /api/rest/v1/register?";
    ssRequest << "id=" << uiId_ << '&' << "delay=" << ( static_cast<int>(server_response_delay_.count()) ) << '&' << "lon=" << dLon_ << '&';
    ssRequest << "lat=" << dLat_ << '&' << "height=" << dHeight_ << '&' << "state=" << state_ << '&' << "error=" << uiError_;
    ssRequest << " HTTP/1.0\r\nHost: " << host_server_ << "\r\nUser-Agent: " << useragent_ << "\r\n\r\n";

}

std::string Client::build_ok_answer( void )
{
    std::ostringstream ssAnswerOk;
    ssAnswerOk << "{\"Text\":\"OK\",\"Id\":" << uiId_ << "}"; 
    return ssAnswerOk.str();
}

std::string Client::build_alarm_answer( void )
{
    std::ostringstream ssAnswerAlarm;
    ssAnswerAlarm << "{\"Text\":\"ALARM\",\"Id\":" << uiId_ << "}"; 
    return ssAnswerAlarm.str();
}

std::string Client::build_wpl_answer( void )
{
    std::ostringstream ssAnswerWpl;
    ssAnswerWpl << "QGC WPL 120";
    return ssAnswerWpl.str();
}

std::chrono::milliseconds Client::getServerResponseDelay( void ) const
{
    return server_response_delay_;
}

void Client::build_wpl_query( void )
{
    std::ostream ssRequestWpl( &request_ );
    ssRequestWpl << "GET /File/data" << uiId_ << ".txt";
    ssRequestWpl << " HTTP/1.0\r\nHost: " << host_server_ << "\r\nUser-Agent: " << useragent_ << "\r\n\r\n";
}

现在...我受到了boost 网站上示例的启发。 如果我启动该程序,它将开始正常每隔2秒询问一次服务器。 我收到正确的答案:

Constructor of the class "Client" called

----------------------------------- 
Request Nr: 1 Socket created Waiting answer from Server...

HTTP/1.1   200   OK 
Server OK, start retrieving data 
I received a ALIVE-Signal from the Server. 
IO Service status: 6

------------------------------------
Request Nr: 2 Socket created Waiting answer from Server...

HTTP/1.1   200   OK 
Server OK, start retrieving data 
I received a ALIVE-Signal from the Server. 
IO Service status: 6

------------------------------------
Request Nr: 3 Socket created Waiting answer from Server...

HTTP/1.1   200   OK 
Server OK, start retrieving data 
I received a ALIVE-Signal from the Server. 
IO Service status: 6

------------------------------------

但是,就我开始请求列表而言,我收到以下信息:

Request Nr: 6
Socket created
Waiting answer from Server...

HTTP/1.1   200   OK
Server OK, start retrieving data

List Data received.
0   1   3   22  1   1000    1   3   51.9896769729347099 8.62269043922424316 35  1   0
1   0   3   16  1   1000    3   1   51.9908133374338917 8.6260378360748291  0   1   0
2   0   3   16  1   5000    3   1   51.9903706872495235 8.62733602523803711 -30 1   1
3   0   3   16  1   1000    3   1   51.9906
IO Service status: 7

这并不是全部列表。 该列表还有两行:

0   1   3   22  1   1000    1   3   231.9896769729347099    83.62269043922424316    35  1   0
1   0   3   16  1   1000    3   1   221.9908133374338917    82.6260378360748291 0   1   0
2   0   3   16  1   5000    3   1   121.9903706872495235    84.62733602523803711    -30 1   1
3   0   3   16  1   1000    3   1   45.99066872495235564

82.62733602523803711 -30 1 1 2 0 3 16 1 5000 3 1 124.9903706872495235 24.62733602324442711 -30 1 1 3 0 3 16 1 1000 3 1 22.99066872495235564 22.62235353533535351 -30 1 1

在我看来,连接(也许我对此不太对劲)突然中断了。 然后从头开始重新开始,并接收剩余的行。 但是我需要立即接收整个列表。 怎么了?


编辑 :非常感谢桥本。 我帮了我很多忙,以了解发生了什么事情以及可以改进什么。 他的助手没有解决问题。 因为,如果我这样做:

void Client::run( void )
{
    if( std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::high_resolution_clock::now() - begin_time_ ) > server_response_delay_ ) 
    {
        begin_time_ = std::chrono::high_resolution_clock::now();

        boost::asio::ip::tcp::resolver::query local_query( host_server_, port_ );

        resolver_.async_resolve( local_query, boost::bind( &Client::handleResolve, this, boost::asio::placeholders::error, boost::asio::placeholders::iterator ) );

        size_t service_status = io_service_.run();

        if( flag_ ) {

            list << &response_;

            std::cout << list.str();
        }

        std::cout << "IO Service status: " << service_status << std::endl << std::endl;

        io_service_.reset();

    }
}

(其中当我请求列表时仅设置了一次标志 ),然后我收到列表的第二部分,但没有收到第一部分。

任何想法?

如果我在那行中没有flag变量,那么连接将在那一刻停滞,并且看不到任何东西。

您的async_read*处理程序缺少bytes_transferred参数。 他们应该有签名

void handler(
  const boost::system::error_code& error, // Result of operation.
  std::size_t bytes_transferred           // Number of bytes copied into the
                                          // buffers. If an error occurred,
                                          // this will be the  number of
                                          // bytes successfully transferred
                                          // prior to the error.
);

请注意,无论绑定到何处,都还需要添加占位符参数。

不过,这不是您的问题所在。 那里的问题是您在阅读响应主体之前先将其打印出来。 注意这一行:

/* HERE I READ A BLOCK OF THE LIST BUT NOT THE WHOLE LIST!!!! */
std::cout << &response_;

在此行之前执行:

boost::asio::async_read( socket_, response_, boost::asio::transfer_at_least(1), 
                         boost::bind(&Client::readContent, this, boost::asio::placeholders::error ) );

好的,现在您可能想知道在阅读之前如何打印出任何身体。 答案是您使用async_read_until读取HTTP状态行和所有标头。 文档说明:

成功执行async_read_until操作后,streambuf可能包含定界符之外的其他数据。 应用程序通常会将这些数据保留在streambuf中,以供后续async_read_until操作进行检查。

因此,您将打印出std::istream没有消耗的其他数据。 那恰好是您列表的第一部分。 然后,您继续阅读其余内容,但不会将其打印出来,因此它仅位于streambuf (在下一个请求中可以看到它)。

读取完成 ,尝试将std::cout行移至Client::run()

void Client::run( void )
{
    if( std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::high_resolution_clock::now() - begin_time_ ) > server_response_delay_ ) 
    {
        begin_time_ = std::chrono::high_resolution_clock::now();

        boost::asio::ip::tcp::resolver::query local_query( host_server_, port_ );

        resolver_.async_resolve( local_query, boost::bind( &Client::handleResolve, this, boost::asio::placeholders::error, boost::asio::placeholders::iterator ) );

        size_t service_status = io_service_.run();

        // ******************************
        // ***** MOVE PRINT TO HERE *****
        // ******************************
        std::cout << &response_;

        std::cout << "IO Service status: " << service_status << std::endl << std::endl;

        io_service_.reset();
    }
}

或者,您可以将其放在Client::readContent()的顶部(如果可以将其大块打印出来)。

暂无
暂无

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

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