Beast Logo

PrevUpHomeNext

Making connections

Connections are established by using the interfaces which already exist for the next layer. For example, making an outgoing connection:

std::string const host = "mywebapp.com";
boost::asio::io_service ios;
boost::asio::ip::tcp::resolver r{ios};
beast::websocket::stream<boost::asio::ip::tcp::socket> ws{ios};
boost::asio::connect(ws.next_layer(),
    r.resolve(boost::asio::ip::tcp::resolver::query{host, "ws"}));

Accepting an incoming connection:

void do_accept(boost::asio::ip::tcp::acceptor& acceptor)
{
    beast::websocket::stream<boost::asio::ip::tcp::socket> ws{acceptor.get_io_service()};
    acceptor.accept(ws.next_layer());
}

When using SSL, which itself wraps a next layer object that is usualy a TCP/IP socket, multiple calls to retrieve the next layer may be required:

beast::websocket::stream<boost::asio::ssl::stream<
    boost::asio::ip::tcp::socket>> ws{ios, ctx};

// connect the underlying TCP/IP socket
ws.next_layer().next_layer().connect(ep);

// perform SSL handshake
ws.next_layer().handshake(boost::asio::ssl::stream_base::client);

// perform WebSocket handshake
ws.handshake("localhost", "/");
[Note] Note

Examples use synchronous interfaces for clarity of exposition.


PrevUpHomeNext