Beast Logo

PrevUpHomeNext

Establishing Connections

Connections are established by invoking functions directly on the next layer object. For example, to make an outgoing connection using a standard TCP/IP socket:

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

Similarly, to accept an incoming connection using a standard TCP/IP socket, pass the next layer object to the acceptor:

boost::asio::ip::tcp::acceptor acceptor{ios};
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 usually a TCP/IP socket, multiple calls to retrieve the next layer may be required. In this example, the websocket stream wraps the SSL stream which wraps the TCP/IP socket:

boost::asio::ip::tcp::endpoint ep;
boost::asio::ssl::context ctx{boost::asio::ssl::context::sslv23};
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