上次写了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 << "Enter Command: ";
std::getline(std::cin, input);
if (input == "quit") {
done = true;
}
else if (input.substr(0, 4) == "send") {
std::stringstream ss(input);
std::string cmd;
std::string message;
ss >> cmd;
std::getline(ss, message);
endpoint.send(message);
}
else if (input.substr(0, 4) == "show") {
endpoint.show();
}
else {
std::cout << "> Unrecognized Command" << std::endl;
}
}
endpoint.close();
return 0;
}
其它两个文件是封装
websocket_endpoint.h文件清单
#ifndef _WEBSOCKET_ENDPOINT_
#define _WEBSOCKET_ENDPOINT_
#include
/*
Title: Web Socket Client
Author: kagula
Date: 2016-11-21
Dependencies: Websocket++、Boost::ASIO
Test Environment: VS2013 Update5, WebSocket++ 0.70, Boost 1.61
Description:
[1]Support connect a web socket server.
[2]If server is crash, client will not follow crash.
*/
namespace kagula
{
class websocket_endpoint {
public:
websocket_endpoint();
~websocket_endpoint();
int connect(std::string const & uri);
void close();
void send(std::string message);
void show();
};
}
#endif
websocket_endpoint.cpp文件清单
#include
#include
#include
#include
#include
#include
#include