boost::asio支持WebSockets吗?

8

我之前发布了一个问题,询问为什么我的服务器(C++和boost::asio编写)无法与客户端(Javascript编写)建立连接。问题出在Javascript Websockets和boost::asio sockets的不同吗?boost::asio是否不支持Websockets?最简单的解决方法是什么?


1
你最好的选择可能是websocket++。它有一个boost::asio传输。目前来看,你需要在asio之上编写自己的websocket协议代码,或者使用像websocket++这样的现有库。 - Sean Cline
@DanMašek,让我问一个不同的问题。使用WebSockets而不是套接字与服务器上的C++应用程序和Java中的Android应用程序进行通信是否很糟糕? - dimitris93
1
@DanMašek 是的,问题在于我想要在Android和浏览器上都有支持。这就是为什么我在考虑如何让它工作。 - dimitris93
在这种情况下,我可能会选择使用WebSockets,这样只需要处理一个服务器实现即可。在Android上,我可能会寻找一些Java WebSocket实现,这样你就不需要在JS中进行通信。 - Dan Mašek
1
记录一下,@DanMašek,Wesocketpp 完美地工作了。谢谢。这绝对是在 C++ 中使用 Websockets 最简单的方法。首先安装 boost,然后将 Websocketpp 作为一个仅包含头文件的库添加到项目中。 - dimitris93
显示剩余3条评论
1个回答

10

Boost.Beast现在是Boost库的一部分,它是在Boost.Asio之上构建的,并按照您的期望方式工作。它附带示例代码和文档。在这里查看:www.boost.org/libs/beast

这是一个完整的程序,向回显服务器发送一条消息:

#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>

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>

// 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 <host> <port> <text>\n" <<
                "Example:\n" <<
                "    websocket-client-sync echo.websocket.org 80 \"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;

        // These objects perform our I/O
        tcp::resolver resolver{ioc};
        websocket::stream<tcp::socket> ws{ioc};

        // 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(ws.next_layer(), results);

        // 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());

        // 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;
}

非常感谢您对Websockets的回复。鉴于您的库现在已成为Boost的一部分,是否有可能更新这个答案?我找不到一些命名空间/类。 - user997112
请问这行代码是干什么用的:req.set(http::field::user_agent, std::string(BOOST_BEAST_VERSION_STRING) + " websocket-client-coro"); - user997112
它没有编译吗?在持续集成上,它对我来说编译并通过了测试。请开一个问题。 - Vinnie Falco
抱歉,我并没有暗示有问题,我只是想知道为什么需要它? - user997112
哦!HTTP需要它(我想)。 - Vinnie Falco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接