Boost beast :: websocket回调函数

时间:2018-04-25 20:33:46

标签: c++ boost websocket

我正在尝试使用Boost beast :: websocket websocket_client_async.cpp示例,并结合websocket_server_async.cpp

如上所述,客户端示例只是建立连接,向服务器发送一个字符串(只是回显),打印回复,关闭和存在。

我试图修改客户端以使会话保持活动状态,以便我可以重复发送/接收字符串。因此,虽然示例代码的on_handshake函数会立即通过ws_.async_write(...)发送字符串,但我将其分离为自己的write(...)函数。

以下是我修改过的session课程:

using tcp = boost::asio::ip::tcp;
namespace websocket = boost::beast::websocket;

void fail(boost::system::error_code ec, char const* what)
{
    std::cerr << what << ": " << ec.message() << "\n";
}

// Sends a WebSocket message and prints the response
class session : public std::enable_shared_from_this<session>
{
    tcp::resolver resolver_;
    websocket::stream<tcp::socket> ws_;
    std::atomic<bool> io_in_progress_;
    boost::beast::multi_buffer buffer_;
    std::string host_;

public:
    // Resolver and socket require an io_context
    explicit session(boost::asio::io_context& ioc) : resolver_(ioc), ws_(ioc) {
        io_in_progress_ = false;
    }

    bool io_in_progress() const {
        return io_in_progress_;
    }

    // +---------------------+
    // | The "open" sequence |
    // +---------------------+
    void open(char const* host, char const* port)
    {
        host_ = host;

        // Look up the domain name
        resolver_.async_resolve(host, port,
            std::bind( &session::on_resolve, shared_from_this(),
                std::placeholders::_1, std::placeholders::_2 )
        );
    }

    void on_resolve(boost::system::error_code ec, tcp::resolver::results_type results)
    {
        if (ec)
            return fail(ec, "resolve");

        boost::asio::async_connect(
            ws_.next_layer(), results.begin(), results.end(),
            std::bind( &session::on_connect, shared_from_this(),
                std::placeholders::_1 )
        );
    }

    void on_connect(boost::system::error_code ec)
    {
        if (ec)
            return fail(ec, "connect");

        ws_.async_handshake(host_, "/",
            std::bind( &session::on_handshake, shared_from_this(),
                std::placeholders::_1 )
        );
    }

    void on_handshake(boost::system::error_code ec)
    {
        if (ec)
            return fail(ec, "handshake");
        else {
            std::cout << "Successful handshake with server.\n";
        }
    }

    // +---------------------------+
    // | The "write/read" sequence |
    // +---------------------------+
    void write(const std::string &text)
    {
        io_in_progress_ = true;
        ws_.async_write(boost::asio::buffer(text),
            std::bind( &session::on_write, shared_from_this(),
                std::placeholders::_1, std::placeholders::_2 )
        );
    }

    void on_write(boost::system::error_code ec, std::size_t bytes_transferred)
    {
        boost::ignore_unused(bytes_transferred);
        if (ec)
            return fail(ec, "write");

        ws_.async_read(buffer_,
            std::bind( &session::on_read, shared_from_this(),
                std::placeholders::_1, std::placeholders::_2 )
        );
    }

    void on_read(boost::system::error_code ec, std::size_t bytes_transferred)
    {
        io_in_progress_ = false; // end of write/read sequence
        boost::ignore_unused(bytes_transferred);
        if (ec)
            return fail(ec, "read");

        std::cout << boost::beast::buffers(buffer_.data()) << std::endl;
    }

    // +----------------------+
    // | The "close" sequence |
    // +----------------------+
    void close()
    {
        io_in_progress_ = true;
        ws_.async_close(websocket::close_code::normal,
            std::bind( &session::on_close, shared_from_this(),
                std::placeholders::_1)
        );
    }

    void on_close(boost::system::error_code ec)
    {
        io_in_progress_ = false; // end of close sequence
        if (ec)
            return fail(ec, "close");

        std::cout << "Socket closed successfully.\n";
    }
};

问题是,虽然连接工作正常并且我可以发送一个字符串,但on_read回调永远不会被命中(除非我做了下面描述的丑陋黑客攻击)。

我的main看起来像这样:

void wait_for_io(std::shared_ptr<session> psession, boost::asio::io_context &ioc)
{
    // Continually try to run the ioc until the callbacks are finally
    // triggered (as indicated by the session::io_in_progress_ flag)
    while (psession->io_in_progress()) {
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
        ioc.run();
    }
}

int main(int argc, char** argv)
{
    // Check command line arguments.
    if (argc != 3) {
        std::cerr << "usage info goes here...\n";
        return EXIT_FAILURE;
    }
    const char *host = argv[1], *port = argv[2];

    boost::asio::io_context ioc;
    std::shared_ptr<session> p = std::make_shared<session>(ioc);
    p->open(host, port);
    ioc.run(); // This works. Connection is established and all callbacks are executed.

    p->write("Hello world"); // String is sent & received by server,
                             // even before calling ioc.run()
                             // However, session::on_read callback is never
                             // reached.

    ioc.run();               // This seems to be ignored and returns immediately, so
    wait_for_io(p, ioc);     // <-- so this hack is necessary

    p->close();              // session::on_close is never reached
    ioc.run();               // Again, this seems to be ignored and returns immediately, so
    wait_for_io(p, ioc);     // <-- this is necessary

    return EXIT_SUCCESS;
}

如果我这样做:

p->write("Hello world");
while(1) {
    std::this_thread::sleep_for(std::chrono::milliseconds(1));
}

我可以确认该字符串已发送&amp;服务器收到 1 ,且session::on_read回调 未到达。

p->close()相同。

但是,如果我添加我奇怪的wait_for_io()函数,一切正常。我很肯定这是一个可怕的黑客,但我无法弄清楚发生了什么。

1 注意:我可以确认邮件是否到达服务器,因为我修改了服务器示例以将任何收到的字符串打印到控制台。这是我制作的唯一修改。回声到客户端功能没有改变。

2 个答案:

答案 0 :(得分:2)

第一次通话后调用io_context::run()的原因无效(如下所示):

boost::asio::io_context ioc;
std::shared_ptr<session> p = std::make_shared<session>(ioc);
p->open(host, port);
ioc.run(); // This works. Connection is established and all callbacks are executed.

是因为必须在io_context::restart()的任何后续调用之前调用函数io_context::run

From the documentation

  

<强> io_context ::重新启动

  重新启动 io_context 以准备后续的run()调用。

必须在run(),run_one的任何第二次或更后一组调用之前调用此函数( ),poll()或poll_one()函数在由于io_context停止或停止工作而返回先前调用这些函数时起作用。在调用restart()之后,io_context对象的stopped()函数将返回false。

答案 1 :(得分:1)

app.use( '/src', express.static( __dirname + '/src' ) ); 只会在没有更多待处理工作时返回。如果您只是确保始终有io_context::run处于待处理状态的待处理呼叫,那么websocket::stream::async_read将永远不会返回,并且不会需要黑客攻击。此外,您将收到服务器发送的所有消息。