pingpong.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. const io = require('socket.io')(8124, { //8124 is the local port we are binding the pingpong server to
  2. pingInterval: 30005, //An interval how often a ping is sent
  3. pingTimeout: 5000, //The time a client has to respont to a ping before it is desired dead
  4. upgradeTimeout: 3000, //The time a client has to fullfill the upgrade
  5. allowUpgrades: true, //Allows upgrading Long-Polling to websockets. This is strongly recommended for connecting for WebGL builds or other browserbased stuff and true is the default.
  6. cookie: false, //We do not need a persistence cookie for the demo - If you are using a load balöance, you might need it.
  7. serveClient: true, //This is not required for communication with our asset but we enable it for a web based testing tool. You can leave it enabled for example to connect your webbased service to the same server (this hosts a js file).
  8. allowEIO3: false, //This is only for testing purpose. We do make sure, that we do not accidentially work with compat mode.
  9. cors: {
  10. origin: "*" //Allow connection from any referrer (most likely this is what you will want for game clients - for WebGL the domain of your sebsite MIGHT also work)
  11. }
  12. });
  13. //This funciton is needed to let some time pass by
  14. function sleep(ms) {
  15. return new Promise((resolve) => {
  16. setTimeout(resolve, ms);
  17. });
  18. }
  19. // App Code starts here
  20. console.log('Starting Socket.IO pingpong server');
  21. io.on('connection', (socket) => {
  22. var cnt = 0;
  23. console.log('[' + (new Date()).toUTCString() + '] unity connecting with SocketID ' + socket.id);
  24. socket.on('PING', async (data) => {
  25. cnt++;
  26. console.log('[' + (new Date()).toUTCString() + '] incoming PING #' + data + ' answering PONG with some jitter...');
  27. await sleep(Math.random() * 2000);
  28. socket.emit('PONG', data);
  29. });
  30. socket.on('disconnect', (reason) => {
  31. console.log('[' + (new Date()).toUTCString() + '] ' + socket.id + ' disconnected after ' + cnt + ' pings. Reason: ' + reason);
  32. });
  33. });