【问题标题】:How to send messages with Websocketpp如何使用 Websocketpp 发送消息
【发布时间】:2016-08-03 14:54:10
【问题描述】:

我有一个用 Javascript 编写的客户端,它运行良好。服务器代码也可以。但是我不知道如何从服务器向客户端发送消息,或者如何结束连接。有谁知道这是怎么做到的吗 ?另外,由于我是一个完整的初学者,我的代码中是否缺少任何东西?我尽量保持简单。

#include <iostream>
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>

typedef websocketpp::server<websocketpp::config::asio> server;

void on_message(websocketpp::connection_hdl hdl, server::message_ptr msg)
{
    std::cout << "Message received:" << std::endl;
    std::cout << msg->get_payload() << std::endl;
}

int main()
{
    server s;
    s.set_message_handler(&on_message);

    s.init_asio();
    s.listen(57252);
    s.start_accept();
    std::cout << "Server Started." << std::endl;
    s.run();
}

【问题讨论】:

    标签: c++ websocket


    【解决方案1】:

    如果您仍在为该代码苦苦挣扎,这里还有另一个很棒的 C++ WebSocket 库,它可能对您来说更易于使用,它仅包含标头并且仅使用 boost。它带有示例代码和文档: http://vinniefalco.github.io/

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

    #include <beast/websocket.hpp>
    #include <beast/buffers_debug.hpp>
    #include <boost/asio.hpp>
    #include <iostream>
    #include <string>
    
    int main()
    {
        // Normal boost::asio setup
        std::string const host = "echo.websocket.org";
        boost::asio::io_service ios;
        boost::asio::ip::tcp::resolver r(ios);
        boost::asio::ip::tcp::socket sock(ios);
        boost::asio::connect(sock,
            r.resolve(boost::asio::ip::tcp::resolver::query{host, "80"}));
    
        using namespace beast::websocket;
    
        // WebSocket connect and send message using beast
        stream<boost::asio::ip::tcp::socket&> ws(sock);
        ws.handshake(host, "/");
        ws.write(boost::asio::buffer("Hello, world!"));
    
        // Receive WebSocket message, print and close using beast
        beast::streambuf sb;
        opcode op;
        ws.read(op, sb);
        ws.close(close_code::normal);
        std::cout <<
            beast::debug::buffers_to_string(sb.data()) << "\n";
    }
    

    【讨论】:

      【解决方案2】:

      我是根据其中一个问题日志制作的:

                  server::connection_ptr con = s.get_con_from_hdl(hdl);
                  std::string resp("BAD");
                  con->send(resp, websocketpp::frame::opcode::text);
      

      对于任何需要检查二进制响应的人: https://github.com/zaphoyd/websocketpp/issues/572

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-24
        • 2021-03-11
        • 2015-12-20
        • 1970-01-01
        • 1970-01-01
        • 2014-04-30
        • 2021-09-10
        • 1970-01-01
        相关资源
        最近更新 更多