Last active
April 18, 2020 04:53
-
-
Save iONinja/ed9f2eb770746e7c236cebbe1ef2c6cf to your computer and use it in GitHub Desktop.
An example of using µWebSockets in a C++ server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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