对来自 websocket 的每个滴答事件做出反应

Reacting to each tick events from the websocket

我想设计我的交易系统来响应我订阅的 websocket 流中的每个报价事件。

所以基本上我有两个选择:

void WebsocketClient::on_write(beast::error_code ec,
                               std::size_t bytes_transferred) {
    boost::ignore_unused(bytes_transferred);

    ws_.async_read(buffer_,
                   beast::bind_front_handler(&WebsocketClient::on_message,
                                             shared_from_this()));
}

void WebsocketClient::on_message(beast::error_code ec,
                                 std::size_t bytes_transferred) {

    // signal generation and sending http request to place new orders here
    // first before calling async_read() below

    std::cout << "Received: " << beast::buffers_to_string(buffer_.cdata())
              << std::endl;

    ws_.async_read(buffer_,
                   beast::bind_front_handler(&WebsocketClient::on_message,
                                             shared_from_this()));
}

或者我可以

void WebsocketClient::on_message(beast::error_code ec,
                            std::size_t bytes_transferred) {
    ws_.async_read(buffer_,
                   beast::bind_front_handler(&WebsocketClient::on_message,
                                             shared_from_this()));

    // signal generation and sending http request to place new orders here after
    // calling async_read()

    std::cout << "Received: " << beast::buffers_to_string(buffer_.cdata())
              << std::endl;
}

请给我你的建议和其他我可以考虑的想法!提前谢谢!

不会有明显的区别,除非

// signal generation and sending http request to place new orders here
// first before calling async_read() below

任一

  • 花费大量时间(IO 线程的设计味道)
  • 通过return/exception
  • 退出函数

那是因为 async_read 根据定义 always returns immediately