Skip to content

Websockets

michaelSaunders edited this page Mar 11, 2018 · 6 revisions

Websocket notes

Connecting to the server client side

$(function () {
   // Correctly decide between ws:// and wss://
   var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
   //set some path "foo/bar" to sever router
   var ws_path = ws_scheme + '://' + window.location.host + "/foo/bar";
   console.log("Connecting to " + ws_path);
   //builds connection
   var socket = new ReconnectingWebSocket(ws_path);

   socket.onmessage = function (message) {
      var data = JSON.parse(message.data);
      
      if (data.error) {
          alert(data.error);
          return;
      }
   }



   //Heartbeat function sends a ping every 10 seconds to server
   setInterval(function() {
      socket.send(JSON.stringify("heartbeat"));
   }, 10000);

Clone this wiki locally