Skip to content

Instantly share code, notes, and snippets.

@iONinja
Last active April 18, 2020 04:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iONinja/ed9f2eb770746e7c236cebbe1ef2c6cf to your computer and use it in GitHub Desktop.
Save iONinja/ed9f2eb770746e7c236cebbe1ef2c6cf to your computer and use it in GitHub Desktop.
An example of using µWebSockets in a C++ server
#include <uWS/uWS.h>
#include <iostream>
unsigned long getTime();
int main(int argc, char *argv[]) {
uWS::Hub h;
h.onMessage([](uWS::WebSocket<uWS::SERVER> *ws, char *data, size_t length, uWS::OpCode opCode) {
ws->send(data, length, opCode);
// Sending binary:
// ws->send(data, size, uWS::OpCode::BINARY);
});
h.onConnection([](uWS::WebSocket<uWS::SERVER> *ws, uWS::HttpRequest req) {
});
h.onDisconnection([](uWS::WebSocket<uWS::SERVER> *ws, int code, char *message, size_t length) {
});
// Uncomment this code for secure WebSockets
// uS::TLS::Context tls = uS::TLS::createContext("ssl/cert.pem", "ssl/key.pem", "key");
if (h.listen(9002/*, tls*/)) {
unsigned long targetDuration = 1000 / 30;
unsigned long lastFrame = getTime();
milliseconds duration(targetDuration);
while (true) {
h.poll();
// Game logic here
unsigned long timeSinceLast = getTime() - lastFrame;
if (timeSinceLast < targetDuration) {
milliseconds intervalDuration(targetDuration - timeSinceLast);
std::this_thread::sleep_for(intervalDuration);
}
lastFrame = getTime();
}
}
return 0;
}
unsigned long getTime() {
return system_clock::now().time_since_epoch() / milliseconds(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment