Websockets

In this tutorial we are going to see how to get started with web sockets. We are going to check how we can use web sockets directly in javascript from the browser, from node nodejs and from a react app.

      

        function initWS(){
          // Create WebSocket connection.
          var ws = new WebSocket(wsdescriptor.url)
          updateReadyState()
      
          // Connection opened
          ws.addEventListener('open', (event) => {
              
              console.log('connection open', event)
              updateReadyState()
              log('connection open')
              // now you can start sending messages
          });
      
          ws.addEventListener('message', (event) => {
              let res = simplyfy(JSON.parse(event.data))
              console.log('message: ', event)
              updateReadyState()
              log('message: ' + event.data + '  ' + res.path + '     ' + JSON.stringify(res.o))
              
          })
      
          ws.addEventListener('close', (event) => {
              updateReadyState()
              console.log('message: ', event)
              log('message: ' + JSON.stringify(JSON.parse(event.data)))
              
          })
      
          ws.addEventListener('error', (event) => {
              updateReadyState()
              console.log('message: ', event)
              log('message: ' + event.data)
              
          })
      
          // no such event, so just inspect state at every other event triggered: ws.addEventListener('readystatechange', (event) => {...
          // run it on instantiation, open, close, error and message(on message not really required)
          function updateReadyState(){
              let states = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']
              let colors = ['gray', 'green', 'red', 'red']
              $('#wsReadyState').text(states[ws.readyState])
              $('#wsReadyState').css('background-color', colors[ws.readyState])
              $('#wsconnect-btn').toggle(states[ws.readyState] === 'CLOSED')
              $('#wsclose-btn').toggle(states[ws.readyState] === 'CONNECTING' || states[ws.readyState] === 'OPEN')
          }
      
          // actions
          $('#wsconnect-btn').click(function(){
              initWS()
          })
      
          $('#wsclose-btn').click(function(){
              ws.close()
              updateReadyState()
          })
      
          $('#send').click(function(){
              ws.send($('#wsMessage').text())
          })
      }