Sends a WebSocket message and prints the response
| 34 | |
| 35 | // Sends a WebSocket message and prints the response |
| 36 | int main(int argc, char** argv) |
| 37 | { |
| 38 | try |
| 39 | { |
| 40 | // Check command line arguments. |
| 41 | if(argc != 4) |
| 42 | { |
| 43 | std::cerr << |
| 44 | "Usage: websocket-client-sync-ssl <host> <port> <text>\n" << |
| 45 | "Example:\n" << |
| 46 | " websocket-client-sync-ssl echo.websocket.org 443 \"Hello, world!\"\n"; |
| 47 | return EXIT_FAILURE; |
| 48 | } |
| 49 | std::string host = argv[1]; |
| 50 | auto const port = argv[2]; |
| 51 | auto const text = argv[3]; |
| 52 | |
| 53 | // The io_context is required for all I/O |
| 54 | net::io_context ioc; |
| 55 | |
| 56 | // The SSL context is required, and holds certificates |
| 57 | ssl::context ctx{ssl::context::tlsv12_client}; |
| 58 | |
| 59 | // Verify the remote server's certificate |
| 60 | ctx.set_verify_mode(ssl::verify_peer); |
| 61 | |
| 62 | // This holds the root certificate used for verification |
| 63 | load_root_certificates(ctx); |
| 64 | |
| 65 | // These objects perform our I/O |
| 66 | tcp::resolver resolver{ioc}; |
| 67 | websocket::stream<ssl::stream<tcp::socket>> ws{ioc, ctx}; |
| 68 | |
| 69 | // Look up the domain name |
| 70 | auto const results = resolver.resolve(host, port); |
| 71 | |
| 72 | // Make the connection on the IP address we get from a lookup |
| 73 | auto ep = net::connect(beast::get_lowest_layer(ws), results); |
| 74 | |
| 75 | // Set SNI Hostname (many hosts need this to handshake successfully) |
| 76 | if(! SSL_set_tlsext_host_name(ws.next_layer().native_handle(), host.c_str())) |
| 77 | { |
| 78 | throw beast::system_error( |
| 79 | static_cast<int>(::ERR_get_error()), |
| 80 | net::error::get_ssl_category()); |
| 81 | } |
| 82 | |
| 83 | // Set the expected hostname in the peer certificate for verification |
| 84 | ws.next_layer().set_verify_callback(ssl::host_name_verification(host)); |
| 85 | |
| 86 | // Update the host_ string. This will provide the value of the |
| 87 | // Host HTTP header during the WebSocket handshake. |
| 88 | // See https://tools.ietf.org/html/rfc7230#section-5.4 |
| 89 | host += ':' + std::to_string(ep.port()); |
| 90 | |
| 91 | // Perform the SSL handshake |
| 92 | ws.next_layer().handshake(ssl::stream_base::client); |
| 93 |
nothing calls this directly
no test coverage detected