js websockets code example

Example 1: javascript websocket example code

var Socket = new WebSocket('ws://' + window.location.hostname + ':81/'); // The '81' here is the Port where the WebSocket server will communicate with
// The instance of the WebSocket() class (i.e. Socket here), must need to be globally defined

Socket.send("pass your data here, and it'll be String"); // This method one can call locally

Example 2: js connect to websocket

var exampleSocket = new WebSocket("wss://www.example.com/socketserver", "protocolOne");

Example 3: web socket background.js example

function createWebSocketConnection() {
    if('WebSocket' in window){
        chrome.storage.local.get("instance", function(data) {
            connect('wss://' + data.instance + '/ws/demoPushNotifications');
        });
    }
}

//Make a websocket connection with the server.
function connect(host) {
    if (websocket === undefined) {
        websocket = new WebSocket(host);
    }

    websocket.onopen = function() {
        chrome.storage.local.get(["username"], function(data) {
            websocket.send(JSON.stringify({userLoginId: data.username}));
        });
    };

    websocket.onmessage = function (event) {
        var received_msg = JSON.parse(event.data);
        var demoNotificationOptions = {
            type: "basic",
            title: received_msg.subject,
            message: received_msg.message,
            iconUrl: "images/demo-icon.png"
        }
        chrome.notifications.create("", demoNotificationOptions);
        updateToolbarBadge();
    };

    //If the websocket is closed but the session is still active, create new connection again
    websocket.onclose = function() {
        websocket = undefined;
        chrome.storage.local.get(['demo_session'], function(data) {
            if (data.demo_session) {
                createWebSocketConnection();
            }
        });
    };
}

//Close the websocket connection
function closeWebSocketConnection(username) {
    if (websocket != null || websocket != undefined) {
        websocket.close();
        websocket = undefined;
    }
}

Example 4: javascript websocket

// npm install --save ws
const WebSocket = require('ws');

const ws = new WebSocket('ws://www.host.com/path');

ws.on('open', function open() {
  ws.send('something');
});

ws.on('message', function incoming(data) {
  console.log(data);
});