C++ uWebSockets 在一个线程中集成事件循环
C++ uWebSockets integrate event loop in one thread
我在我的 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,其中我有自己的自定义事件循环。这是一个 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 工作。