简体   繁体   中英

C++ boost asio tcp socket reading old data

I'm a Boost asio newcomer. I've got a tcp server client pair program running, but when I run a new client, that client picks up all the old writes too. I'm reading/writing with async_read / async_write. So a server and a client may have been running for a while and sent 100~ packets back and forth. When I open a second client and receive on it, I receive all 100 of the old server-sent packets! "localhost" is used for the ip_address.

Is there some way to clear the buffer or something? Perhaps there's another way other than close the old socket and create a new socket?

The read/write calls (not used in this order, just copied both of the calls from where I used them):

boost::array<char, 1024> buf;
boost::array<char, 1024> rbuf;
boost::asio::async_write(socket_, 
    boost::asio::buffer(buf.c_array(), 
    buf.size()),strand_.wrap(boost::bind(&async_tcp_client::handle_send_msg,
    this,boost::asio::placeholders::error)));

boost::asio::async_read(socket_, boost::asio::buffer(rbuf.c_array(), rbuf.size()),
    strand_.wrap(boost::bind(&async_tcp_client::handle_read,
    this, boost::asio::placeholders::error,
    boost::asio::placeholders::bytes_transferred)));

It's not clear to me how your buffers are scoped. You will need a buffer per connection, one each for both reading and writing. You also need to ensure they stay within scope as long as the asynchronous operation is active.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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