gda2004
gda2004

Reputation: 746

boost asio read buffer

My Question is what is the best way to read off a boost tcp socket when you do not know the message size? this is a sample. I have simply put a size of 10. code is in different headers but I did not feel the need to include it all

///////////// hpp

typedef boost::asio::ip::tcp::resolver TResolver;
typedef boost::asio::ip::tcp::resolver::query TResolverQuery;
typedef boost::asio::ip::tcp::endpoint Tendpoint;
typedef boost::asio::ip::tcp::socket Tsocket;
typedef boost::asio::ip::tcp::acceptor Tacceptor;
#define Tsize 10

//////////// cpp

while(true)
{
    cout<<"recieve"<<endl;
    boost::shared_ptr< Tacceptor > acceptor(new boost::asio::ip::tcp::acceptor(*m_io_service));
    boost::system::error_code ec;
    TResolverQuery query(this->getHost(), boost::lexical_cast< std::string >( this->getPort() ));
    TResolver resolver( *m_io_service );
    Tendpoint endpoint = *resolver.resolve( query );
    acceptor->open( endpoint.protocol() );
    acceptor->set_option( boost::asio::ip::tcp::acceptor::reuse_address( true ) );
    acceptor->bind( endpoint );
    acceptor->listen();
    boost::shared_ptr< Tsocket > socknew(new Tsocket( *m_io_service ));
    acceptor->accept( *socknew,endpoint);
    boost::array<char, Tsize> buf;
    boost::asio::read(*socknew,boost::asio::buffer(buf), ec);
    cout.write(buf.data(),Tsize);cout << std::endl;
    socknew->shutdown( boost::asio::ip::tcp::socket::shutdown_both, ec );
    cout<<"threadId "<< boost::this_thread::get_id()<<endl;        
}

Upvotes: 2

Views: 4132

Answers (2)

gda2004
gda2004

Reputation: 746

I found a solution to my problem which is that I can use a while not eof to read off the socket and push_back on a vector which does work. I may create a wiki on here as a reference point.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409442

The two most common methods is to use a protocol that either contains the length of the message, or has a end-of-message marker.

Upvotes: 2

Related Questions