最近需要在c++程序中用到websocket技术,上网查了一下,找到四个库:libwebsocket, websocketpp, mongoose, boost.beast. 因为项目已经依赖于boost了,而且版本也比较新1.68,可以直接用boost.beast(从boost 1.66起可用),因此就不费心搞别的了,直接用boost.beast来实现。
先直接从样例代码开始,做了少许修改,就实现了同步版本的客户端。
client.cpp
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <cstdlib>
#include <iostream>
#include <string>
using tcp = boost::asio::ip::tcp; // from <boost/asio/ip.tcp.hpp>
namespace websocket = boost::beast::websocket; // from <boost/beast/websocket.hpp>
// Sends a WebSocket message and prints the response
int main(int argc, char** argv)
{
try {
// Check command line arguments.
if (argc != 4) {
std::cerr <<
"Usage: client <host> <port> <text>\n" <<
"Example:\n" <<
" client echo.websocket.org 80 \"Hello, world!\"\n";
return EXIT_FAILURE;
}
auto const host = argv[1];
auto const port = argv[2];
auto const text = argv[3];
// The io_context is required for all I/O
boost::asio::io_context ioc;
// These objects perform our I/O
tcp::resolver resolver{ioc};
websocket::stream<tcp::so