[英]How to connect to websocket server using boost C++
我的 websocket 服務器 URL 是ws://localhost/webstream/wsocket我正在嘗試創建一個使用 boost 連接到該服務器的 C++ websocket 客戶端
tcp::resolver resolver{ioc};
_pws = new websocket::stream<tcp::socket>(ioc);
// Look up the domain name
// my server is http://localhost/webstream/wsocket
_host = "localhost";
_port = 80;
auto const results = resolver.resolve(_host, std::to_string(_port));
if(results.size() == 0)
{
std::cout<<"failed to connect to websocket server"<<std::endl;
delete _pws;
_pws = nullptr;
return;
}
// Make the connection on the IP address we get from a lookup
net::connect(_pws->next_layer(), results.begin(), results.end());
// Set a decorator to change the User-Agent of the handshake
_pws->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");
}));
_pws->handshake(host, "/");
但是我無法連接到服務器。 如何設置路徑“/webstream/wsocket”進行連接。 '''
我試過的:
i tried with
_host = "localhost/webstream/wsocket";
_port = 80;
_pws->handshake(host, "/webstream/wsocket");
但沒有連接在boost庫中,我們如何指定websocket服務器的路徑
這是我用來連接到我的 url 的示例。 我正在從我的客戶端發送字符串數據,並使用我的服務器從端口讀取它。
如果您能夠使用郵遞員連接到它,我相信這會奏效。
auto const address = boost::asio::ip::make_address("127.0.0.1");
auto const port = static_cast<unsigned short>(std::atoi("9898"));
boost::asio::io_context ioc { 1 };
tcp::acceptor acceptor { ioc, { address, port } };
char againStart;
while (1) {
tcp::socket socket { ioc };
acceptor.accept(socket);
std::cout << "socket accepted" << std::endl;
std::thread { [q = std::move(socket)]() mutable {
boost::beast::websocket::stream<tcp::socket> ws { std::move(q) };
ws.accept();
while (1) {
boost::beast::flat_buffer buffer;
ws.read(buffer);
auto out = boost::beast::buffers_to_string(buffer.cdata());
stringVal = out;
int argument = argument + 1;
ofstream file;
file.open("filePath.txt", ios::out | ios::app); //, ios::out | ios::app used to add to another line instead of changing entire file
file << stringVal;
file << argument << endl;
file.close();
}
} }.detach();
我還保留了一些我用來從緩沖區讀取數據的行。 理論上,這應該與您的 url 作為其客戶端服務器綁定一起使用。
類似於這個問題
訪問websocket url的正確方式: ws://localhost:5000/webstream/wsocket
,需要設置
host_ = "localhost";
port_ = 5000;
解析端點並連接后,握手時需要路徑/webstream/wsocket
_pws->handshake(host, "/webstream/wsocket")
這樣就可以成功建立websocket連接了
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.