上次写了WebSocket服务端,这次工作当中需要一个用C++实现的WebSocket客户端,写好后这里记一下,免得以后忘记。
本示例共有三个文件组成,依赖Websocket++第三方库
其中main.cpp是使用示例
#include
#include
#include
#include "websocket_endpoint.h"
int main(int argc, char **argv)
{
bool done = false;
std::string input;
kagula::websocket_endpoint endpoint;
endpoint.connect("ws://localhost:9002");
while (!done) {
std::cout
> cmd;
std::getline(ss, message);
endpoint.send(message);
}
else if (input.substr(0, 4) == "show") {
endpoint.show();
}
else {
std::cout
get_response_header("Server");
}
// if connection failed, the function will be invoke.
void on_fail(ws_client *client, websocketpp::connection_hdl hdl) {
m_status = "Failed";
ws_client::connection_ptr con = client->get_con_from_hdl(hdl);
m_server = con->get_response_header("Server");
m_error_reason = con->get_ec().message();
}
void on_close(ws_client *client, websocketpp::connection_hdl hdl) {
m_status = "Closed";
ws_client::connection_ptr con = client->get_con_from_hdl(hdl);
std::stringstream s;
s
get_payload()));
}
}
websocketpp::connection_hdl get_hdl() const {
return m_hdl;
}
std::string get_status() const {
return m_status;
}
std::string get_uri() const {
return m_uri;
}
void record_sent_message(std::string message) {
m_messages.push_back(">> " + message);
}
friend std::ostream & operator
