官方的example中仅仅输出到控制台,而且不支持中文,这里我加入了ansi到utf8的转换,使用utf8就能正常解析中文。
server:
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// Official repository: https://github.com/boostorg/beast
//------------------------------------------------------------------------------
// Example: WebSocket client, synchronous
//------------------------------------------------------------------------------
//[example_websocket_client
#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>
#include <locale>
#include <codecvt>
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
std::wstring string_to_wstring(const std::string &s)
using default_convert = std::codecvt<wchar_t, char, std::mbstate_t>;
static std::wstring_convert<default_convert>conv(new default_convert("CHS"));
return conv.from_bytes(s);
std::string wstring_to_string(const std::wstring &s)
using default_convert = std::codecvt<wchar_t, char, std::mbstate_t>;
static std::wstring_convert<default_convert>conv(new default_convert("CHS"));
return conv.to_bytes(s);
std::string ansi_to_utf8(const std::string &s)
static std::wstring_convert<std::codecvt_utf8<wchar_t> > conv;
return conv.to_bytes(string_to_wstring(s));
std::string utf8_to_ansi(const std::string& s)
static std::wstring_convert<std::codecvt_utf8<wchar_t> > conv;
return wstring_to_string(conv.from_bytes(s));
// Sends a WebSocket message and prints the response
int main(int argc, char** argv)
// The io_context is required for all I/O
net::io_context ioc;
// These objects perform our I/O
tcp::resolver resolver{ ioc };
websocket::stream<tcp::socket> ws{ ioc };
auto const address = net::ip::make_address("192.168.0.27");
auto const port = static_cast<unsigned short>(std::atoi("80"));
tcp::endpoint endpoint{ address, port };
// Look up the domain name
auto const results = resolver.resolve(endpoint);
// Make the connection on the IP address we get from a lookup
net::connect(ws.next_layer(), results.begin(), results.end());
//net::connect(ws.next_layer(), host, port);
// Set a decorator to change the User-Agent of the handshake
ws.set_option(websocket::stream_base::decorator(
[](websocket::request_type& req)
req.set(http::field::user_agent,
std::string(BOOST_BEAST_VERSION_STRING) +
" websocket-client-coro");
// Perform the websocket handshake
ws.handshake("0.0.0.0", "/");
while (true)
std::string text;
std::cin >> text;
// Send the message
ws.write(net::buffer(ansi_to_utf8(text)));
// This buffer will hold the incoming message
beast::flat_buffer buffer;
// Read a message into our buffer
ws.read(buffer);
std::string out;
out = beast::buffers_to_string(buffer.cdata());
std::cout << utf8_to_ansi(out) << std::endl;
// Close the WebSocket connection
ws.close(websocket::close_code::normal);
catch (std::exception const& e)
std::cerr << "Error: " << e.what() << std::endl;
return EXIT_FAILURE;
return EXIT_SUCCESS;
client:
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// Official repository: https://github.com/boostorg/beast
//------------------------------------------------------------------------------
// Example: WebSocket server, synchronous
//------------------------------------------------------------------------------
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <string>
#include <thread>
#include <codecvt>
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
std::wstring string_to_wstring(const std::string& s)
using default_convert = std::codecvt<wchar_t, char, std::mbstate_t>;
static std::wstring_convert<default_convert>conv(new default_convert("CHS"));
return conv.from_bytes(s);
std::string wstring_to_string(const std::wstring& s)
using default_convert = std::codecvt<wchar_t, char, std::mbstate_t>;
static std::wstring_convert<default_convert>conv(new default_convert("CHS"));
return conv.to_bytes(s);
std::string ansi_to_utf8(const std::string& s)
static std::wstring_convert<std::codecvt_utf8<wchar_t> > conv;
return conv.to_bytes(string_to_wstring(s));
std::string utf8_to_ansi(const std::string& s)
static std::wstring_convert<std::codecvt_utf8<wchar_t> > conv;
return wstring_to_string(conv.from_bytes(s));
//------------------------------------------------------------------------------
// Echoes back all received WebSocket messages
do_session(tcp::socket& socket)
// Construct the stream by moving in the socket
websocket::stream<tcp::socket> ws{ std::move(socket) };
// Set a decorator to change the Server of the handshake
ws.set_option(websocket::stream_base::decorator(
[](websocket::response_type& res)
res.set(http::field::server,
std::string(BOOST_BEAST_VERSION_STRING) +
" websocket-server-sync");
// Accept the websocket handshake
ws.accept();
for (;;)
// This buffer will hold the incoming message
beast::flat_buffer buffer;
// Read a message
ws.read(buffer);
auto out = beast::buffers_to_string(buffer.cdata());
std::cout << utf8_to_ansi(out) << std::endl;
// Echo the message back
ws.text(ws.got_text());
ws.write(buffer.data());
catch (beast::system_error const& se)
// This indicates that the session was closed
if (se.code() != websocket::error::closed)
std::cerr << "Error: " << se.code().message() << std::endl;
catch (std::exception const& e)
std::cerr << "Error: " << e.what() << std::endl;
//------------------------------------------------------------------------------
int main(int argc, char* argv[])
auto const address = net::ip::make_address("0.0.0.0");
auto const port = static_cast<unsigned short>(std::atoi("80"));
// The io_context is required for all I/O
net::io_context ioc{ 1 };
// The acceptor receives incoming connections
tcp::acceptor acceptor{ ioc, {address, port} };
for (;;)
// This will receive the new connection
tcp::socket socket{ ioc };
// Block until we get a connection
acceptor.accept(socket);
// Launch the session, transferring ownership of the socket
std::thread{ std::bind(
&do_session,
std::move(socket)) }.detach();
catch (const std::exception & e)
std::cerr << "Error: " << e.what() << std::endl;
return EXIT_FAILURE;
领导安排实现一个websocket客户端做测试用,因为工位电脑上的环境只有vs2019和boost1.78.0,所以只能基于boost.beast开发。
擅长Qt并且有Qt开发环境的用QWebsocket更方便。
官方的example中仅仅输出到控制台,而且不支持中文,这里我加入了ansi到utf8的转换,使用utf8就能正常解析中文。
注:项目需包含boost库
客户端代码:
#include<time.h>
#include <boost/beast/core.hp
上次写了
WebSocket服务端,这次工作当中需要一个用
C++实现的
WebSocket客户端,写好后这里记一下,免得以后忘记。
本示例共有三个文件组成,依赖
Websocket++第三方库
其中main.cpp是使用示例
#include <io
stream>
#include <
string>
#include <s
stream>
#include "
websocket_endpoint.h"
int main(int argc, char **argv)
boost库
websocket协程
客户端
基于
boost标准
C++库,使用协程和
beast实现
websocket客户端。需要连接多少个
websocket服务器协议地址,则创建多少个协程以及相应的处理函数即可。
#include <
boost/
beast/core.hpp>
#include <
boost/
beast/
websocket.hpp>
#include <
boost/asio/spawn.hpp>
#include <c
stdlib>
昨天公司刚刚提出微信小程序过审必须支持wss,当时蒙圈开始以为
C++要加入OpenSSL,来支持wss。后来上网查找发现nginx进行代理中转(不需要更改任何
C++代码)就可以实现协议支持,不禁感慨nginx强大与自己知识薄弱。 言归正传。
1、
C++支持WS请求(略)
四、Beast中的network
由于http、websocket仅涉及tcp,因此在beast范围内,也仅涉及tcp协议,Beast的网络操作基于Asio,但Beast的一个目标似乎是做一个完整的系统(猜测),因此beast将涉及到的网络数据操作都“重写”的一遍(一些是简单包装,一些是扩展),例如Asio空间被重新命名为net,对std:bind也扩展为bind_handler和bind_front_handler。
beast设计了两套stream,一是用于http的...
1.1 背景
项目中会遇到让已有的
C++服务端程序增加
WebSocket协议支持,与前端进行通讯。Github上有不少开源的
C++代码可以参考,比较知名的如
websocketcpp,
beast, u
WebSockets,re
stbed等等,不过即便有这些代码参考,也难以快速移植程序到你的现在的
C++服务器端程序里,原因大致有下面几点:
之上的简单Http服务器和客户端
美丽是之上的一层,它提供了创建Http服务器或客户端的工具。 Beauty允许创建同步或异步服务器和客户端,并基于添加一些信号和计时器管理
Http或Http / s服务器或客户端
同步或异步API
服务器支持的响应延迟
使用占位符的服务器轻松路由
包括计时器和信号支持
可启动和可停止的应用程序事件循环
可自定义的线程池大小
进行中:Swagger描述API
一台服务器
# include < beauty>
int main ()
// Create a server
beauty::server server;
// Add a default '/' route
server. get ( " / " , []( const auto & req, auto & re
之前分享过一篇使用libwebsockets的文章,这篇分享一个api使用更加简单基于c++11的websocket开发工具uwebsockets。
我目前基于的github上GitHub - uNetworking/uWebSockets at v0.14的版本进行开发,大家如果打开之后会发现,这个是五年前的版本,是的,新版本需要uSockets和c++17,因为平时工作多数部署再centos7或者6上,如果用新版本需要升级gcc,所以我用的比较早的版本。
因为网上资料比较少,这里也是由于自己使用..