WebSocket Client (2.0+ only, WinRT only)
The WebSocket client class is used to create and maintain a connection to a WebSocket endpoint.To create a client instance, you use pass in a URI specifying where the client should connect to.
web::experimental::web_sockets::client::websocket_client client(U("ws://localhost:1234"));
Once you have your client, you must connect to the remote endpoint using the connect() function. This function returns a task which can be waited upon.
client.connect().then([](){ /* We've finished connecting. */ });
Once the client is connected, you can start sending and receiving data. Like the rest of casablanca, this is done in an asynchronous way.
websocket_outgoing_message msg; msg.set_utf8_message("I am a UTF-8 string! (Or close enough...)"); client.send(msg).then([](){ /* Successfully sent the message. */ }); client.receive().then([](websocket_incoming_message msg) { return msg.extract_string(); }).then([](std::string body) { std::cout << body << std::endl; });
We also support sending binary messages.
websocket_outgoing_message msg; concurrency::streams::producer_consumer_buffer<uint8_t> buf; std::vector<uint8_t> body(6); memcpy(&body[0], "a\0b\0c\0", 6); auto send_task = buf.putn(&body[0], body.size()).then([&](size_t length) { msg.set_binary_message(buf.create_istream(), length); return client.send(msg); }).then([](pplx::task<void> t) { try { t.get(); } catch(const websocket_exception& ex) { std::cout << ex.what(); } }); send_task.wait();
Once you're done with the client, you can close it.
client.close().then([](){ /* Successfully closed the connection. */ });