C 或 C++ websocket 客户端工作示例
Posted
技术标签:
【中文标题】C 或 C++ websocket 客户端工作示例【英文标题】:C or C++ websocket client working example 【发布时间】:2021-11-02 03:50:48 【问题描述】:我是 C 和 C++ 的新手。我正在尝试为可以连接到 websocket 服务器的 C 或 C++ 中的任何 websocket 库找到小的工作示例。所以,到目前为止,我已经探索了 uWebsockets、libwebsockets、websocketpp 和 boost::beast。他们似乎都没有详细的文档。我在 https://www.boost.org/doc/libs/develop/libs/beast/doc/html/beast/examples.html 的 boost::beast 网站上找到了一些示例,但是它们也不起作用。如果我能找到一个可行的示例,我可以研究它以了解更多信息。
我试过这个命令,它正在连接到雅虎端点: wscat -c "wss://streamer.finance.yahoo.com/" -H '来源:https://finance.yahoo.com' 并打印一个随机字符串。
wscat -c "wss://streamer.finance.yahoo.com/" -H 'Origin: https://finance.yahoo.com'
Connected (press CTRL+C to quit)
> "subscribe":["ES=F","YM=F","NQ=F","RTY=F","CL=F","GC=F","SI=F","EURUSD=X","^TNX","^VIX","GBPUSD=X","JPY=X","BTC-USD","^CMC200","^FTSE","^N225","INTC"]
< CgdCVEMtVVNEFduJQ0cYoP2/2/VeIgNVU0QqA0NDQzApOAFFlmEuP0iAgL/AwQJVlwxHR139ST1HZYBWqUNqC0JpdGNvaW4gVVNEsAGAgL/AwQLYAQTgAYCAv8DBAugBgIC/wMEC8gEDQlRD+gENQ29pbk1hcmtldENhcIECAAAAADbvcUGJAgAAhAG9ZWtC
< CgdCVEMtVVNEFQTtQkcY4KbH2/VeIgNVU0QqA0NDQzApOAFFUznHPkiAgMzPwQJVlwxHR139ST1HZQBrQUNqC0JpdGNvaW4gVVNEsAGAgMzPwQLYAQTgAYCAzM/BAugBgIDMz8EC8gEDQlRD+gENQ29pbk1hcmtldENhcIECAAAAADbvcUGJAgAAND7DT2tC
我试过这样的简单python代码
from websocket import create_connection
import json
import pprint
import re
import time
import datetime
def subscribe_yahoo ():
headers =
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0',
'Accept': '*/*',
'Accept-Language': 'en-US,en;q=0.5',
'Sec-WebSocket-Version': '13',
'Origin': 'https://finance.yahoo.com',
'Sec-WebSocket-Key': 'nNtGm/0ZJcrR+goawlJz9w==',
'DNT': '1',
'Connection': 'keep-alive, Upgrade',
'Sec-Fetch-Dest': 'websocket',
'Sec-Fetch-Mode': 'websocket' ,
'Sec-Fetch-Site': 'same-site' ,
'Pragma': 'no-cache',
'Cache-Control': 'no-cache',
'Upgrade': 'websocket',
messages='"subscribe":["INTC"]'
# Initialize the headers needed for the websocket connection
initMessages = [
messages,
]
websocketUri = """wss://streamer.finance.yahoo.com/"""
print (websocketUri)
ws = create_connection(websocketUri,header=headers)
for m in initMessages:
print ("sending ", m)
ws.send(m)
message_stream = True
i=0
while message_stream:
result = ws.recv()
i=i+1
print (str(i),' -- ', result)
subscribe_yahoo()
而且它也在工作。
如果有人可以帮助我编写在 c 或 c++ 中类似的代码,我将不胜感激。
有人可以解释是否可以使用firefox源代码https://searchfox.org/mozilla-central/source/netwerk/protocol/websocket在C++中实现websocket客户端,或者是否有人成功使用firefox代码作为websocket客户端。
我没有要求任何推荐的图书馆,任何图书馆都可以满足我的学习目的。 在此先感谢:)
以下示例按原样从https://www.boost.org/doc/libs/develop/libs/beast/example/websocket/client/sync-ssl/websocket_client_sync_ssl.cpp复制
#include "example/common/root_certificates.hpp"
#include <boost/beast/core.hpp>
#include <boost/beast/ssl.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/beast/websocket/ssl.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl/stream.hpp>
#include <cstdlib>
#include <iostream>
#include <string>
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>
namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.hpp>
using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.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: websocket-client-sync-ssl <host> <port> <text>\n" <<
"Example:\n" <<
" websocket-client-sync-ssl echo.websocket.org 443 \"Hello, world!\"\n";
return EXIT_FAILURE;
std::string host = argv[1];
auto const port = argv[2];
auto const text = argv[3];
// The io_context is required for all I/O
net::io_context ioc;
// The SSL context is required, and holds certificates
ssl::context ctxssl::context::tlsv12_client;
// This holds the root certificate used for verification
load_root_certificates(ctx);
// These objects perform our I/O
tcp::resolver resolverioc;
websocket::stream<beast::ssl_stream<tcp::socket>> wsioc, ctx;
// Look up the domain name
auto const results = resolver.resolve(host, port);
// Make the connection on the IP address we get from a lookup
auto ep = net::connect(get_lowest_layer(ws), results);
// Set SNI Hostname (many hosts need this to handshake successfully)
if(! SSL_set_tlsext_host_name(ws.next_layer().native_handle(), host.c_str()))
throw beast::system_error(
beast::error_code(
static_cast<int>(::ERR_get_error()),
net::error::get_ssl_category()),
"Failed to set SNI Hostname");
// Update the host_ string. This will provide the value of the
// Host HTTP header during the WebSocket handshake.
// See https://tools.ietf.org/html/rfc7230#section-5.4
host += ':' + std::to_string(ep.port());
// Perform the SSL handshake
ws.next_layer().handshake(ssl::stream_base::client);
// 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(host, "/");
// Send the message
ws.write(net::buffer(std::string(text)));
// This buffer will hold the incoming message
beast::flat_buffer buffer;
// Read a message into our buffer
ws.read(buffer);
// Close the WebSocket connection
ws.close(websocket::close_code::normal);
// If we get here then the connection is closed gracefully
// The make_printable() function helps print a ConstBufferSequence
std::cout << beast::make_printable(buffer.data()) << std::endl;
catch(std::exception const& e)
std::cerr << "Error: " << e.what() << std::endl;
return EXIT_FAILURE;
return EXIT_SUCCESS;
编译使用:
g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
g++ boost_test.cpp -o websocket-client-sync-ssl -lboost_system -pthread -lssl -lcrypto
./websocket-client-sync-ssl
Usage: websocket-client-sync-ssl <host> <port> <text>
Example:
websocket-client-sync-ssl echo.websocket.org 443 "Hello, world!"
然后按照建议:
./websocket-client-sync-ssl echo.websocket.org 443 "Hello, world!"
没用
/websocket-client-sync-ssl streamer.finance.yahoo.com 443 "Hello, world!"
Error: The WebSocket stream was gracefully closed at both endpoints
【问题讨论】:
我也是 C/C++ 新手。实际上,我从未听说过这种语言。你能链接一些关于这种语言的信息吗? 请注意,这里要求图书馆推荐是特别离题的——请查看What topics can I ask about here?。请多关注您的问题以提出一个具体问题。提到的所有这些库都应该可以工作。如果您尝试过某事并遇到问题,请出示该代码,描述问题并就该代码提出问题。 “他们似乎都没有详细的文档”。欢迎来到开源软件的世界。现实情况是,这种级别的文档很常见,您需要学习使用它。我知道 websocketpp 文档虽然不完美,但确实足以开始使用。再次显示您尝试过的代码,以便我们回答更具体的问题。 @kaylum:我编译了这个例子:boost.org/doc/libs/develop/libs/beast/example/websocket/client/…;并尝试使用代码推荐的命令,这也不起作用。 ``` websocket-client-sync-ssl echo.websocket.org 443 \"你好,世界!\"\n" ``` @MichaelAuten 没有 C/C++ 语言。有 C 或 C++,两种不同的语言。选择一个。 【参考方案1】:这是一个使用 easywsclient 的快速演示:
#include "easywsclient.hpp"
#include <iostream>
#include <string>
#include <memory>
#include <mutex>
#include <deque>
#include <thread>
#include <chrono>
#include <atomic>
// a simple, thread-safe queue with (mostly) non-blocking reads and writes
namespace non_blocking
template <class T>
class Queue
mutable std::mutex m;
std::deque<T> data;
public:
void push(T const &input)
std::lock_guard<std::mutex> L(m);
data.push_back(input);
bool pop(T &output)
std::lock_guard<std::mutex> L(m);
if (data.empty())
return false;
output = data.front();
data.pop_front();
return true;
;
// eastwsclient isn't thread safe, so this is a really simple
// thread-safe wrapper for it.
class Ws
std::thread runner;
non_blocking::Queue<std::string> outgoing;
non_blocking::Queue<std::string> incoming;
std::atomic<bool> running true ;
public:
void send(std::string const &s) outgoing.push(s);
bool recv(std::string &s) return incoming.pop(s);
Ws(std::string url)
using easywsclient::WebSocket;
runner = std::thread([=]
std::unique_ptr<WebSocket> ws(WebSocket::from_url(url));
while (running)
if (ws->getReadyState() == WebSocket::CLOSED)
break;
std::string data;
if (outgoing.pop(data))
ws->send(data);
ws->poll();
ws->dispatch([&](const std::string & message)
incoming.push(message);
);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
ws->close();
ws->poll();
);
void close() running = false;
~Ws() if (runner.joinable()) runner.join();
;
int main()
Ws socket("ws://localhost:40800");
std::atomic<bool> runtrue;
auto receiver = std::thread([&]
std::string s;
while (run)
if (socket.recv(s))
std::cout << s << '\n';
std::this_thread::sleep_for(std::chrono::milliseconds(10));
);
std::string line;
while (std::getline(std::cin, line))
socket.send(line);
run = false;
receiver.join();
socket.close();
我使用Crow在服务器上对其进行了测试:
// A simple websocket-based echo server
#include "crow_all.h"
int main()
crow::SimpleApp app;
CROW_ROUTE(app, "/")
.websocket()
.onopen([&](crow::websocket::connection& conn)
CROW_LOG_INFO << "new websocket connection";
)
.onclose([&](crow::websocket::connection& conn, const std::string& reason)
CROW_LOG_INFO << "websocket connection closed: " << reason;
)
.onmessage([&](crow::websocket::connection& conn, const std::string& data, bool is_binary)
std::cout << "Received message: " << data << "\n";
if (is_binary)
conn.send_binary(data);
else
conn.send_text(data);
);
app.port(40800)
.multithreaded()
.run();
我使用这个 Makefile 构建:
both: client server
INC = -Iexternal/easywsclient/ -Iexternal/crow/build/amalgamate/
LIBS = -leasywsclient -Lexternal/easywsclient -lboost_system -pthread
CXXFLAGS += $INC
client: client.o
$CXX -o client client.o $LIBS
server: server.o
$CXX -o server server.o $LIBS
要进行测试,请启动服务器,然后启动客户端。然后你可以在客户端中输入随机的东西。它将被发送到服务器,在那里打印出来,回显给客户端,然后再打印出来。几乎是典型的、无用的(但足以证明他们正在通信)网络演示之类的东西。
【讨论】:
谢谢,我编译了你的代码,它工作正常,但是当我将 main 中的第一行更改为Ws socket("wss://streamer.finance.yahoo.com/")
时出现错误。 ERROR: Could not parse WebSocket url: wss://streamer.finance.yahoo.com/
.
我认为easywsclient不支持ssl
@MichaelAuten:对不起,我没有注意到你想做 ssl。为此,我会改用IXWebSockets。需要做更多工作,但支持 TLS。
@JerryCoffin:非常感谢,IXWebSockets 成功了! git 有带有 wss 端点的工作示例。我安装libdeflate
后编译的示例。代码使用g++ hello1.cpp -lixwebsocket -pthread -lz -ldeflate -lssl -lcrypto
编译以上是关于C 或 C++ websocket 客户端工作示例的主要内容,如果未能解决你的问题,请参考以下文章
使用 websocketpp 库连接到 c++ websocket 服务器