WebSocket js code example

Example 1: nodejs websocket tutorial

/*
Author: Logan Smith - Perkins
*/

// Importing the http library, used to start servers
const http = require('http');
// Importing the websocket library which is used to interface between webpage and nodejs
const WebSocketServer = require('websocket').server;
// This server is created using the http createServer function, which enables the user to create a http connection with a webpage
const server =- http.createServer();
// The server then listens on the port specified
server.listen(7000);

// We then create a new variable which will store the actual server I'll be running
const wsServer = new WebSocketServer({
	// Then we set the parameter of httpServer to the server variable that we said that would be listening on the port specified
	httpServer : server
});

// Next we check if someome is trying to connect to the server, i.e. the name request, it's requesting access to the server
wsServer.on('request', function(request){
	// We store the actual connection as a variable and we accept that client to connect to this server
	const connection = request.accept(null, request.origin);
	// This function is run when this client sends a message to the server.
	connection.on('message', function(message){
		// We print out to the console the recieved message decoded to utf8
		console.log("Recieved Message: " + message.utf8Data);
		// Then we send specifically to this connection back a message
		connection.sendUTF("Hello this is the websocket server.");
	});
	// This code is run when the user disconnects from the server.
	connection.on('close', function(reasonCode, description){
		// We just print to the console that a client has disconnected from the server.
		console.log("A client has disconnected.");
	});
});

Example 2: 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 3: js connect to websocket

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

Example 4: 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 5: 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);
});