Evan
Evan

Reputation: 67

Read message in its entirety with Boost.ASIO [WebSocket]

I'm writing a simple WebSocket server using Boost.ASIO. Right now, I'm working on trying to process the handshake. My problem is, it doesn't look like there's a predefined length for handshake messages sent from the client.

My question is, how can I stop reading the handshake when the message ends?

I've first tried async_read_some where I read for a specified number of bytes.

void Connection::readMessage()
{
    auto self(shared_from_this());
    w_socket.async_read_some(boost::asio::buffer(w_data, max_length),
        [this, self](boost::system::error_code ec, std::size_t length)  // Lambda function
        {
            if (!ec)
            {
                std::cout << w_data << std::endl;
            }
        });
}

The above code gave me this result: https://i.sstatic.net/qFlIU.png

Then I tried to research further and found that async_read_until (reading until consecutive new lines are found) temporarily fixes it for handshake messages, but that doesn't guarantee that it will stop.

void Connection::readMessage()
{
    auto self(shared_from_this());
    boost::asio::async_read_until(w_socket, streambuffer, "\r\n\r\n",
        [this, self](boost::system::error_code ec, std::size_t length)  // Lambda function
        {
            if (!ec)
            {
                std::istream is(&streambuffer);
                std::getline(is, w_data_s);

                std::cout << w_data_s << std::endl;
            }
        });
}

The above code gave this result: https://i.sstatic.net/GfRL9.png

Or maybe a better question would be, which would be best to handle handshake messages and which would be best to handle plain messages after handshake passes (dataframes and stuff).

Upvotes: 0

Views: 499

Answers (1)

Oliver Clancy
Oliver Clancy

Reputation: 116

Looking at the websocket spec here: http://datatracker.ietf.org/doc/rfc6455/?include_text=1 you are on the right track.

Use async_read_until to handle the handshake as it has undefined length but is delimited the same as http, and then, personally for exchange of the actual data after completing the handshake, switch to using async_read using either, a predefined header of fixed length which describes the length of a following body, or specify your own completion condition. You can of course carry on using async_read_until if you don't mind delimiting your messages in some fixed way.

Upvotes: 1

Related Questions