如何使用 websocket websocketpp 发送和接收消息?

问题描述 投票:1回答:1

如何使用 websocket websocketpp 收发消息?

我有一段C ++的小代码,我试图使用websocketpp库。

我使用的是客户端服务器可用的例子,但终端只显示它已经连接。

https:/github.comzaphoydwebsocketpp。

我是一个C ++的初学者,所以我很感激我可以帮助的关注。因为我正在学习的语言和技术websocket。

服务器

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


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

class utility_server {
public:
    utility_server() {
        // Set logging settings
        m_endpoint.set_error_channels(websocketpp::log::elevel::all);
        m_endpoint.set_access_channels(websocketpp::log::alevel::all ^ websocketpp::log::alevel::frame_payload);

        // Initialize Asio
        m_endpoint.init_asio();

        // Set the default message handler to the echo handler
        m_endpoint.set_message_handler(std::bind(
            &utility_server::echo_handler, this,
            std::placeholders::_1, std::placeholders::_2
        ));
    }

    void echo_handler(websocketpp::connection_hdl hdl, server::message_ptr msg) {
        // write a new message
        m_endpoint.send(hdl, msg->get_payload(), msg->get_opcode());
    }

    void run() {
        // Listen on port 9002
        m_endpoint.listen(9002);

        // Queues a connection accept operation
        m_endpoint.start_accept();

        // Start the Asio io_service run loop
        m_endpoint.run();
    }
private:
    server m_endpoint;
};

int main()
{
    utility_server s;
    s.run();
    return 0;
}

客户

#include <websocketpp/config/asio_no_tls_client.hpp>
#include <websocketpp/client.hpp>

#include <iostream>

typedef websocketpp::client<websocketpp::config::asio_client> client;

using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
using websocketpp::lib::bind;

// pull out the type of messages sent by our config
typedef websocketpp::config::asio_client::message_type::ptr message_ptr;

// This message handler will be invoked once for each incoming message. It
// prints the message and then sends a copy of the message back to the server.
void on_message(client* c, websocketpp::connection_hdl hdl, message_ptr msg) {
    std::cout << "on_message called with hdl: " << hdl.lock().get()
        << " and message: " << msg->get_payload()
        << std::endl;


    websocketpp::lib::error_code ec;

    c->send(hdl, msg->get_payload(), msg->get_opcode(), ec);
    if (ec) {
        std::cout << "Echo failed because: " << ec.message() << std::endl;
    }
}

int main(int argc, char* argv[]) {
    // Create a client endpoint
    client c;

    std::string uri = "ws://localhost:9002";

    if (argc == 2) {
        uri = argv[1];
    }

    try {
        // Set logging to be pretty verbose (everything except message payloads)
        c.set_access_channels(websocketpp::log::alevel::all);
        c.clear_access_channels(websocketpp::log::alevel::frame_payload);

        // Initialize ASIO
        c.init_asio();

        // Register our message handler
        c.set_message_handler(bind(&on_message, &c, ::_1, ::_2));

        websocketpp::lib::error_code ec;
        client::connection_ptr con = c.get_connection(uri, ec);
        if (ec) {
            std::cout << "could not create connection because: " << ec.message() << std::endl;
            return 0;
        }

        // Note that connect here only requests a connection. No network messages are
        // exchanged until the event loop starts running in the next line.
        c.connect(con);

        // Start the ASIO io_service run loop
        // this will cause a single connection to be made to the server. c.run()
        // will exit when this connection is closed.
        c.run();
    }
    catch (websocketpp::exception const& e) {
        std::cout << e.what() << std::endl;
    }
}
c++ web-services webserver
1个回答
0
投票

你需要使用客户端实例调用send()方法;各种重载都在文档中列出了 此处. EDIT: 我可以看到其实你已经在调用它了,但是用错了地方。因为它在消息处理程序中,它只有在收到消息时才会发送,而服务器代码本身不发送任何消息,所以客户端的发送永远不会触发。而服务器代码本身不发送任何消息,所以客户端的send永远不会触发。websocketpp的例子将send放在open handler中,但除了演示之外,这是一个非常无用的用例。

更多的时候,您希望直接从您的应用程序代码中调用send。棘手的是,在你对客户端做任何事情之前,你必须调用run(),而run是一个阻塞调用(这意味着你不能在之后调用send)。答案是有一个线程专门用来调用run(),这样你就可以在主线程上调用send()(或者你想要的任何一个线程)。

既然你说你是C++新手,我建议你先学习一下线程:学习如何优雅地启动和停止线程,学习线程安全。在C++中,有几种使用线程的方法,但在这种情况下,我建议看看std::thread。

一旦你了解了如何在C++中使用线程,那么就试着把它建立在你的应用程序中。最终,为你的客户机创建一个处理线程和发送消息等的类会是一个好主意。

一旦你得到了一些工作,我建议你读一读这本书 websocketpp FAQ)特别是 "如何干净利落地退出一个基于Asio运输的程序 "部分。

© www.soinside.com 2019 - 2024. All rights reserved.