我在我的 C++ 项目中使用 uWebSockets,其中我有自己的自定义事件循环。这是一个 while 循环,每次执行之间都有可变的延迟。它看起来像这样:
while (true) {
std::this_thread::sleep_for (variableTime);
// Execute logic
}
我之前一直使用另一个线程来执行逻辑,但我想将 uWebSockets 循环与我的循环集成。像这样的事情:
#include <iostream>
#include <uWS/uWS.h>
using namespace std;
int main () {
uWS::Hub h;
h.onMessage([](uWS::WebSocket<uWS::SERVER> *ws, char *message, size_t length, uWS::OpCode opCode) {
ws->send(message, length, opCode);
});
if (h.listen(3000)) {
h.run();
}
while (true) {
std::this_thread::sleep_for (variableTime);
h.getMessages(); // <-- doesn't call `onMessage` until this is executed
// Execute logic
}
}
我该如何去做呢?
最佳答案
今天我也有同样的问题。经过一番挖掘源代码后,我想我找到了答案。
看来您正在寻找的是最近添加的 ( https://github.com/uNetworking/uWebSockets/pull/762 ) Node::Poll (Hub 继承 Node)函数,该函数在程序主循环中使用非阻塞。我认为它应该与您想要的 getMessages 完全一样。
关于C++ uWebSockets 在一个线程中集成事件循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45889889/