Avoid creating onMessage function per WS client - javascript

Following ws's instructions to create a WebSocket server:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
An onMessage callback named incoming is created for every client, am I right?
Imagine having two million clients. This code would create two million functions. Is there a way to avoid this? Something like this would be wonderful:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('message', function incoming(ws, message) {
// Access to ws object
console.log('received: %s', message);
});

How about:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
function handleMessage(message) {
console.log('received: %s', message);
}
wss.on('message', handleMessage);

Related

error: Typeerror: wss.broadcast in not a function

I made a chat app and I am trying to broadcast the message, but I am getting this error: "error: Typeerror: wss.broadcast in not a function".
this is the server code:
const WebSocket = require('ws');
let broadcast_msg;
const PORT = 5000;
const wss = new WebSocket.Server({
port: PORT
});
wss.on("connection", (ws) =>{
ws.on('message', function incoming(message){
console.log('received: ', message);
wss.broadcast(message)
});
});
console.log("Server is liestening on port " + PORT);
This is what I am currently doing as well
wss.broadcast = function broadcast(msg){
wss.clients.forEach(function each(client){
client.send(msg);
});
};
But this also give me back multiple responses depending on my number of clients. Does anyone know how to prevent this?
Because Class: WebSocket.Server don't have broadcast function,you can read ws api to confirm.
You can foreach wss.clients to send meesages one by one to broadcast.
I change my code to that:
wss.on("connection", (ws) =>{
ws.on('message', function incoming(message){
console.log('received: ', message);
wss.broadcast(message);
});
});
wss.broadcast = function broadcast(msg){
wss.clients.forEach(function each(client){
client.send(msg);
});
};

How to read headers from a websocket connection

i try to send an information on the header of a webSocket, and read it on the server on connection.
things like:
Client code is as simple as:
ws = await WebSocket.connect('ws://localhost.com:36485', headers: {
'codeName': 'Something',
},);
the server code:
var WebSocketServer = require('ws').Server
, wss = new WebSocketServer({ port: 36485 });
wss.on('connection', function connection(ws) {
console.log(ws.upgradeReq.headers);
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
});
the exception that i have is :
Type Error: Cannot read property 'headers' of undefined
If you're using this ws module on NPM, then way you get access to the headers like this (taken directly from the documentation):
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function(ws, req) {
console.log(req.headers);
});
thanks for your help, for some reason its not working with 'ws' but its working fine with 'webSoket'.
var webSocketServer = require('websocket').server;
var http = require('http');
wsServer.on('request', function(request){
console.log(request.httpRequest.headers['codename']);
}

How to make pure Node.js websocket client?

Assuming that web sockets based on TCP I have created a simple TCP client, but I cannot get any response from echo.websocket.org. What am I doing wrong?
const connectionData: any = {
protocol: 'ws:',
host: 'echo.websocket.org',
port: '80'
}
var client = new net.Socket();
client.connect(connectionData, function () {
console.log('Connected');
client.write('Reply this.');
});
client.on('data', function (data) {
console.log('Received: ' + data);
});
client.on('close', function () {
console.log('Connection closed');
});

How to send broadcast to all connected client in node js

I'm a newbie working with an application with MEAN stack. It is an IoT based application and using nodejs as a backend.
I have a scenario in which I have to send a broadcast to each connected clients which can only open the Socket and can wait for any incoming data. unless like a web-browser they can not perform any event and till now I have already gone through the Socket.IO and Express.IO but couldn't find anything which can be helpful to achieve what I want send raw data to open socket connections'
Is there any other Node module to achieve this. ?
Here is the code using WebSocketServer,
const express = require('express');
const http = require('http');
const url = require('url');
const WebSocket = require('ws');
const app = express();
app.use(function (req, res) {
res.send({ msg: "hello" });
});
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
wss.on('connection', function connection(ws) {
ws.on('message', function(message) {
wss.broadcast(message);
}
}
wss.broadcast = function broadcast(msg) {
console.log(msg);
wss.clients.forEach(function each(client) {
client.send(msg);
});
};
server.listen(8080, function listening() {
console.log('Listening on %d', server.address().port);
});
Now, my query is when this code will be executed,
wss.on('connection', function connection(ws) {
ws.on('message', function(message) {
wss.broadcast(message);
}
}
var WebSocketServer = require("ws").Server;
var wss = new WebSocketServer({port:8100});
wss.on('connection', function connection(ws) {
ws.on('message', function(message) {
wss.broadcast(message);
}
}
wss.broadcast = function broadcast(msg) {
console.log(msg);
wss.clients.forEach(function each(client) {
client.send(msg);
});
};
Try the following code to broadcast message from server to every client.
wss.clients.forEach(function(client) {
client.send(data.toString());
});
Demo server code,
const WebSocket = require('ws')
const wss = new WebSocket.Server({ port: 2055 },()=>{
console.log('server started')
})
wss.on('connection', (ws) => {
ws.on('message', (data) => {
console.log('data received \n '+ data)
wss.clients.forEach(function(client) {
client.send(data.toString());
});
})
})
wss.on('listening',()=>{
console.log('listening on 2055')
})

Does React Native require more websocket configuration?

I´ve set up a websocket connection by following this "guide":
https://facebook.github.io/react-native/docs/network.html
My code so far, first block in React Native:
ws = new WebSocket("ws://localhost:8087/");
ws.onopen = () => {
ws.send('something');
};
ws.onmessage = (e) => {
this.setState({ message: e.data });
};
Second block, my node server:
const WebSocketServer = require('ws').Server;
const wss = new WebSocketServer({ port: 8087 });
const messages = [];
wss.on('connection', (ws) => {
messages.forEach((message) => {
ws.send(message);
});
ws.on('message', (message) => {
messages.push(message);
console.log('Message Received: %s', message);
wss.clients.forEach((conn) => {
conn.send(message);
});
});
});
It works fine but when I deploy, do I need to set up a another server with websocket connection other than the one React Native provides?

Categories