MCPcopy Create free account
hub / github.com/boostorg/beast / main

Function main

example/websocket/client/sync-ssl/websocket_client_sync_ssl.cpp:36–129  ·  view source on GitHub ↗

Sends a WebSocket message and prints the response

Source from the content-addressed store, hash-verified

34
35// Sends a WebSocket message and prints the response
36int 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

Callers

nothing calls this directly

Calls 12

load_root_certificatesFunction · 0.85
c_strMethod · 0.80
set_optionMethod · 0.80
whatMethod · 0.80
connectFunction · 0.50
decoratorClass · 0.50
native_handleMethod · 0.45
handshakeMethod · 0.45
writeMethod · 0.45
readMethod · 0.45
closeMethod · 0.45
dataMethod · 0.45

Tested by

no test coverage detected