I have a NodeJS web app running. I have a WebSocketServer running. I can communicate with my app via a WebSocket connection made from my javascript on the client machine fine. Here's the nodejs server-side code snippet of relevance:
var WebSocket = require('ws');
var WebSocketServer = require('ws').Server;
var server = app.listen(process.env.VCAP_APP_PORT || 3000, function () {
console.log('Server started on port: ' + server.address().port);
});
wss.on('connection', function (ws) {
ws.on('message', function (message, flags) {
if (flags.binary) {
var value1 = message.readDoubleLE(0);
var value2 = message.readInt16LE(8);
var value3 = message.readInt8(10);
//message.writeDoubleLE(8.5,0);
ws.send(message, {
binary: true
});
} else {
if (message == "injest") {
ws.send("requested: " + message);
} else if (message == "something") {
wss.clients[0].send('server side initiated call');
} else {
ws.send("received text: " + message);
}
}
});
// ws.send('something'); // Sent when connection opened.
});
So you see, all very simple.
Here 's my problem. How can I access this WebServer from the NodeJS code of the server-side app itself?
I tried the below:
var ws = new WebSocket("ws://localhost:443");
ws.on('message', function (message) {
wss.clients[0].send('server side initiated call 1 ');
});
ws.on('close', function (code) {
wss.clients[0].send('server side initiated call 2 ');
});
ws.on('error', function (error) {
wss.clients[0].send(error.toString());
});
ws.send("k");
The error function is triggered with ECONNREFUSED 127.0.0.1:443.
I specified no port when I set the server up. If I do then the calls to the server from my client html page fail.
So in brief how can I set up a WebSocket client in NodeJS to access a WebSocketServer created in that app?
Do not use localhost. Substitute the 127.0.0.1 for it.
Instantiate the Server
let WebSocketServer = require("ws").Server;
let ws = new WebSocketServer({port: 9090});
ws.on('connection', function (ws) {
console.log(nHelp.chalk.red.bold('Server WebSocket was connected.'));
// Add the listener for that particular websocket connection instance.
ws.on('message', function (data) {
//code goes here for what you need
});
ws.on('close', function () {
console.log('websocket connection closed!');
});
});
You can open other ports and routes (example for Express) in the same file, or other ports for WS as well btw.
The above is not code for Secure WS server for TLS. that is a bit different.
Related
I've been through to ws documentation and have copied and pasted their external http/s server example character for character. When I run the server I don't get any errors but when I go to my browser and navigate to the local host on the specified port number, the page is stuck in this infinite load state. What am I doing wrong?
This is what I have for my server app (copied from ws example):
const fs = require('fs');
const https = require('https');
const WebSocket = require('ws');
const server = https.createServer({
cert: fs.readFileSync('backendSSL/backend.crt', 'utf8'),
key: fs.readFileSync('backendSSL/backend.key', 'utf8')
});
const wss = new WebSocket.Server({ server });
wss.on('connection', function connection(ws) {
console.log("new client connected");
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
server.listen(8080);
This is what I have in my html file:
// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');
// Connection opened
socket.addEventListener('open', function (event) {
socket.send('Hello Server!');
});
// Listen for messages
socket.addEventListener('message', function (event) {
console.log('Message from server ', event.data);
});
when i print client in console logconsole.log(client ${client}); it shows undefined.
I think i should do something in my client code but don't know what.
Server code -
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws, request, client) {
console.log(`client ${client}`);
ws.on('message', function message(msg) {
console.log(`Received message ${msg}`);
});
});
client code-
const Websocket = require('ws');
const ws = new Websocket('ws://localhost:8081');
function noop() {}
ws.on("message", function(event){
console.log(event);
});
const ping = function() {
ws.ping(noop);
}
setInterval(ping, 30000);
ws doesn't support client out of the box.
See: https://www.npmjs.com/package/ws#client-authentication
the gist of it is that you need to use an HTTP server to listen to any connections (not using ws to listen) and "manual" emit the connection event with additional data (like client).
I have a uWebSockets server as it seems to be a lot more performance friendly than socket.io servers.
So I have a server and its connected fine and after some trouble I got the index.html client side to connect, but now I'm not able to push events to the server from the client side. What am I doing wrong?
var WebSocketServer = require('uws').Server,
express = require('express'),
path = require('path'),
app = express(),
server = require('http').createServer(),
createEngine = require('node-twig').createEngine;
var wss = new WebSocketServer({server: server});
wss.on('connection', function (ws) {
ws.on('join', function (value) {
console.log('SOMEONE JUST JOINED');
});
ws.on('close', function () {
//console.log('stopping client interval');
clearInterval(id);
});
});
server.on('request', app);
server.listen(8080, function () {
console.log('Listening on http://localhost:8080');
});
index.html
<script>
var host = window.document.location.host.replace(/:.*/, '');
var server = new WebSocket('ws://' + host + ':8080');
server.onmessage = function (event) {
updateStats(JSON.parse(event.data));
};
server.onopen = function (event) {
server.send("Here's some text that the server is urgently awaiting!");
server.send('join');
};
function something() {
console.log('WORKED');
server.send('join');
}
</script>
You don't have an event listener setup on the server side that does receive and react on the message. Like
ws.on('message', function (msg) {
// Do something with the message received from the client
});
Im trying to create a node websocket for messaging and broadcasting using openshift. Below is my code.
var WebSocketServer = require('ws').Server;
var http = require('http');
var ipaddr = opneshift_ip;
var port = openshift_port;
var server = http.createServer();
var wss = new WebSocketServer({server: server, path: '/connectserv'});
wss.broadcast = function(data) {
for(var i in this.clients) {
console.log(this.clients[i]);
this.clients[i].send(data);
}
};
wss.on('connection', function(ws) {
console.log('a client connected');
ws.on('message', function(data) {
console.log('>>> ' + data);
ws.send('got '+data);
if (data == 'broadcst') {
console.log('broadcst');
wss.broadcast('Hi All');
}
});
ws.on('close', function() {
console.log('Connection closed!');
});
ws.on('error', function(e) {
console.log(e);
});
});
console.log('Listening at IP ' + ipaddr +' on port '+port);
server.listen(port,ipaddr);
When any client connects, console writes "a client connected".
When any client sends message, console writes ">>> message" and im getting the same at client as well ("got message")
But when multiple clients are connected, if i want to broadcast a message to all connected clients, i send "broadcst" as message. Than goes into
if (data == 'broadcst') {
console.log('broadcst');
wss.broadcast('Hi All');
}
But only the client which sends get the message.
How to make all clients to get the message?
Does each client creates separate session?
How to use redis here?
Any quick help appreciated.
Thanks.
Try
wss.broadcast = function(data) {
for(var i in wss.clients) {
console.log(wss.clients[i]);
wss.clients[i].send(data);
}
};
broadcasting with wss
I found a simple websocket server in nodejs.
var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({
port: 8080
});
var clientsCount = 0;
console.log('clients,rss,heapTotal,heapUsed');
setInterval(function() {
console.log('%d,%d,%d,%d', clientsCount,
process.memoryUsage().rss,
process.memoryUsage().heapTotal,
process.memoryUsage().heapUsed);
}, 10000);
wss.on('connection', function(ws) {
clientsCount++;
console.log(clientsCount);
ws.on('message', function(message) {
console.log(message);
});
ws.send('something');
ws.on('close', function() {
clientsCount--;
})
});
The script works fine but sometimes when a client connects and sends a data, the server doesn't accept the message; ws.on('message', function(message){...}); doesn't seem to trigger when the event occurs.