js websockets code example
Example 1: javascript websocket example code
var Socket = new WebSocket('ws://' + window.location.hostname + ':81/');
Socket.send("pass your data here, and it'll be String");
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');
});
}
}
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();
};
websocket.onclose = function() {
websocket = undefined;
chrome.storage.local.get(['demo_session'], function(data) {
if (data.demo_session) {
createWebSocketConnection();
}
});
};
}
function closeWebSocketConnection(username) {
if (websocket != null || websocket != undefined) {
websocket.close();
websocket = undefined;
}
}
Example 4: javascript websocket
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);
});