Skip to content

Instantly share code, notes, and snippets.

@purefan
Last active May 10, 2018 11:56
Show Gist options
  • Save purefan/dc5c1d161eae703b1b75bf2cf32874c0 to your computer and use it in GitHub Desktop.
Save purefan/dc5c1d161eae703b1b75bf2cf32874c0 to your computer and use it in GitHub Desktop.
cpp ws client - not working
#include "stdafx.h"
#include <websocketpp/config/asio_no_tls_client.hpp>
#include <websocketpp/client.hpp>
#include <Windows.h>
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <future>
typedef websocketpp::client<websocketpp::config::asio_client> client;
using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
using websocketpp::lib::bind;
typedef websocketpp::config::asio_client::message_type::ptr message_ptr;
void send_message(client* c, websocketpp::connection_hdl hdl, std::string msg) {
std::cout << "[send_message] " << msg << std::endl;
auto future = std::async(std::launch::async, [c, hdl, msg] {
c->send(hdl, msg, websocketpp::frame::opcode::text);
std::cout << "Actually sent it";
});
}
void on_message(client* c, websocketpp::connection_hdl hdl, message_ptr msg) {
websocketpp::lib::error_code ec;
if (ec) {
std::cout << "Echo failed because: " << ec.message() << std::endl;
}
else {
std::cout << "[debug on_message]" << msg->get_payload() << std::endl;
}
}
void on_open(client* c, websocketpp::connection_hdl hdl) {
bool keep_running = true;
do {
auto future = std::async(std::launch::async, [c, hdl]() {
std::cout << "listening to keyboard...";
std::string input = "";
std::getline(std::cin, input);
std::cout << "and this is what keyboard said: " << input << std::endl;
return input;
});
const std::string input = future.get();
if (input == "exit") {
keep_running = false;
}
else {
std::cout << "[cpp to ws] " << input;
send_message(c, hdl, input);
}
} while (keep_running);
}
int main(int argc, char* argv[]) {
// Create a client endpoint
client c;
std::string uri = "ws://localhost:8080";
if (argc == 2) {
uri = argv[1];
}
try {
// Initialize ASIO
c.init_asio();
// Register our message handler
c.set_message_handler(bind(&on_message, &c, ::_1, ::_2));
c.set_open_handler(bind(&on_open, &c, ::_1));
websocketpp::lib::error_code ec;
client::connection_ptr con = c.get_connection(uri, ec);
if (ec) {
std::cout << "could not create connection because: " << ec.message() << std::endl;
return 0;
}
c.connect(con);
c.run();
}
catch (websocketpp::exception const & e) {
std::cout << "-- client exception --" << std::endl << e.what() << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment