Refactor WebSocket, HTTP examples:

fix #297, fix #488

* Errors are checked and reported
* More comments explaining what is going on
* The connection is gracefully closed

WebSocket:

* Messages are drained before closing
This commit is contained in:
Vinnie Falco
2017-07-20 08:15:27 -07:00
parent 298bf5fbb1
commit 74891560ae
6 changed files with 260 additions and 139 deletions
+50 -10
View File
@@ -11,35 +11,75 @@
#include <beast/http.hpp>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include <cstdlib>
#include <iostream>
#include <string>
int main()
{
// Normal boost::asio setup
std::string const host = "www.example.com";
// A helper for reporting errors
auto const fail =
[](std::string what, beast::error_code ec)
{
std::cerr << what << ": " << ec.message() << std::endl;
std::cerr.flush();
return EXIT_FAILURE;
};
boost::system::error_code ec;
// Set up an asio socket
boost::asio::io_service ios;
boost::asio::ip::tcp::resolver r{ios};
boost::asio::ip::tcp::socket sock{ios};
boost::asio::connect(sock,
r.resolve(boost::asio::ip::tcp::resolver::query{host, "http"}));
// Send HTTP request using beast
// Look up the domain name
std::string const host = "www.example.com";
auto const lookup = r.resolve(boost::asio::ip::tcp::resolver::query{host, "http"}, ec);
if(ec)
return fail("resolve", ec);
// Make the connection on the IP address we get from a lookup
boost::asio::connect(sock, lookup, ec);
if(ec)
return fail("connect", ec);
// Set up an HTTP GET request message
beast::http::request<beast::http::string_body> req;
req.method(beast::http::verb::get);
req.target("/");
req.version = 11;
req.insert(beast::http::field::host, host + ":" +
req.set(beast::http::field::host, host + ":" +
boost::lexical_cast<std::string>(sock.remote_endpoint().port()));
req.insert(beast::http::field::user_agent, "Beast");
req.set(beast::http::field::user_agent, "Beast");
req.prepare();
beast::http::write(sock, req);
// Receive and print HTTP response using beast
// Write the HTTP request to the remote host
beast::http::write(sock, req, ec);
if(ec)
return fail("write", ec);
// This buffer is used for reading and must be persisted
beast::flat_buffer b;
// Declare a container to hold the response
beast::http::response<beast::http::dynamic_body> res;
beast::http::read(sock, b, res);
// Read the response
beast::http::read(sock, b, res, ec);
if(ec)
return fail("read", ec);
// Write the message to standard out
std::cout << res << std::endl;
// Gracefully close the socket
sock.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
if(ec)
return fail("shutdown", ec);
// If we get here then the connection is closed gracefully
return EXIT_SUCCESS;
}
//]