Websocket Client

Here is a very simple JS implementation of connecting to the websocket and receiving data

    const WebSocket = require('ws');
    var that = this;
    function connect() {
        var url = 'ws://192.168.1.10/eventsocket';
        var ws = new WebSocket(url);
        console.log('attempt connection to ' + url);
        ws.onopen = function() {
            console.log('connection to ' + url + ' established');
        };

        ws.onmessage = function(e) {
            try {
                var jsonData = JSON.parse(e.data);
            } catch (e) {
                console.log('Invalid JSON data received from websocket', e.data);
                return;
            }
        };

        ws.onclose = function(e) {
          console.log('HE Eventsocket is closed. Reconnect will be attempted in 1 second. ', e.reason);
          setTimeout(function() {
            connect();
          }, 1000);
        };

        ws.onerror = function(err) {
          console.log('HE Eventsocket encountered error: ', err.message, 'Closing socket');
          ws.close();
        };

    }
    connect();
1 Like