Commit 4f2f6855 authored by Alex Hultman's avatar Alex Hultman

Update multithreading example, make use of reuse-port

parent e7775f76
#include <uWS/uWS.h>
#include <iostream>
#include <string>
#include <thread>
using namespace std;
#include <algorithm>
#include <iostream>
using namespace uWS;
int main() {
std::vector<std::thread *> threads(std::thread::hardware_concurrency());
std::transform(threads.begin(), threads.end(), threads.begin(), [](std::thread *t) {
return new std::thread([]() {
uWS::Hub h;
#define THREADS 4
uWS::Hub *threadedServer[THREADS];
h.onMessage([](uWS::WebSocket<uWS::SERVER> *ws, char *message, size_t length, uWS::OpCode opCode) {
ws->send(message, length, opCode);
});
// This makes use of the SO_REUSEPORT of the Linux kernel
// Other solutions include listening to one port per thread
// with or without some kind of proxy inbetween
if (!h.listen(3000, nullptr, uS::ListenOptions::REUSE_PORT)) {
std::cout << "Failed to listen" << std::endl;
}
h.run();
});
});
int main()
{
try {
// you need at least one server listening to a port
Hub h;
h.onConnection([&](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req){
int t = rand() % THREADS;
cout << "Transfering connection to thread " << t << endl;
ws.transfer(&threadedServer[t]->getDefaultGroup<uWS::SERVER>());
});
// launch the threads with their servers
for (int i = 0; i < THREADS; i++) {
new thread([i]{
// register our events
threadedServer[i] = new Hub();
threadedServer[i]->onDisconnection([&i](WebSocket<uWS::SERVER> ws, int code, char *message, size_t length){
cout << "Disconnection on thread " << i << endl;
});
threadedServer[i]->onMessage([&i](uWS::WebSocket<uWS::SERVER> ws, char *message, size_t length, uWS::OpCode code){
cout << "Message on thread " << i << ": " << string(message, length) << endl;
ws.send((char *) message, length, code);
});
threadedServer[i]->getDefaultGroup<uWS::SERVER>().addAsync();
threadedServer[i]->run();
});
}
h.getDefaultGroup<uWS::SERVER>().addAsync();
h.listen(3000);
h.run();
} catch (...) {
cout << "ERR_LISTEN" << endl;
}
return 0;
std::for_each(threads.begin(), threads.end(), [](std::thread *t) {
t->join();
});
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment