开发者

How to flush the socket using boost

I am implementing a server that sends xml to clients using boost. The problem I am facing is that t开发者_开发问答he buffer doesn't get sent immediately and accumulates to a point then sends the whole thing. This cause a problem on my client side, when it parses the xml, it may have incomplete xml tag (incomplete message). Is there a way in boost to flush out the socket whenever it needs to send out a message? Below is server's write code.

void 
ClientConnection::handle_write(const boost::system::error_code& error)
{

    if (!error)
    {

        m_push_message_queue.pop_front ();
        if (!m_push_message_queue.empty () && !m_disconnected)
        {

             boost::asio::async_write(m_socket,
            boost::asio::buffer(m_push_message_queue.front().data(), 
                        m_push_message_queue.front().length()),
                boost::bind(&ClientConnection::handle_write, this,
                boost::asio::placeholders::error));
        }
    }
    else
    {
      std::err << "Error writting out message...\n";
      m_disconnected = true;
      m_server->DisconnectedClient (this);

    }
}


Typically when creating applications using TCP byte streams the sender sends a fixed length header so the receiver knows how many bytes to expect. Then the receiver reads that many bytes and parses the resulting buffer into an XML object.


I assume you are using TCP connection. TCP is stream type, so you can't assume your packet will come in one big packet. You need to fix your communication design, by sending size length first like San Miller answer, or sending flag or delimiter after all xml data has been sent.


Assuming you are definitely going to have some data on the socket you want to clear, you could do something like this:

void fulsh_socket()
{
    boost::asio::streambuf b;
    boost::asio::streambuf::mutable_buffers_type bufs = b.prepare(BUFFER_SIZE);
    std::size_t bytes = socket_.receive(bufs); // !!! This will block until some data becomes available
    b.commit(bytes);
    boost::asio::socket_base::bytes_readable command(true);
    socket_.io_control(command); 

    while(command.get())
    {
        bufs = b.prepare(BUFFER_SIZE);
        bytes = socket_.receive(bufs);
        b.commit(bytes);
        socket_.io_control(command); // reset for bytes pending
    }
    return;
}

where socket_ is a member variable.

HTH

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜