WebSocket js code example
Example 1: nodejs websocket tutorial
const http = require('http');
const WebSocketServer = require('websocket').server;
const server =- http.createServer();
server.listen(7000);
const wsServer = new WebSocketServer({
httpServer : server
});
wsServer.on('request', function(request){
const connection = request.accept(null, request.origin);
connection.on('message', function(message){
console.log("Recieved Message: " + message.utf8Data);
connection.sendUTF("Hello this is the websocket server.");
});
connection.on('close', function(reasonCode, description){
console.log("A client has disconnected.");
});
});
Example 2: 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 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');
});
}
}
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 5: 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);
});