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
Related
I have a socket server in node. When it revives a new message, it writes it to the socket. But from which it has revived, writes to the corresponding socket, not all connections.
Server.js
var server = net.createServer(function(sock){
console.log('new client connected');
sock.on('data', function(data) {
console.log('Server received');
// ** NOT sending to all clients **
sock.write('broadcasting to others...');
});
});
Client.js
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('Client connected to: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
client.write('Client is connected!!');
});
client.on('data', function(data) {
console.log('Client received: ' + data);
});
How can I broadcast one client message to all other clients?
Following up on my suggestion to use a Set to keep track of all the connected sockets, this is one way to implement that. This implementation maintains that Set as connections come and go by listening to both the connect event and the end event.
This implementation also supports a desirable feature to send to all connected sockets EXCEPT the one that triggered the event (which I think is what your situation would want):
// Set of all currently connected sockets
const connectedSockets = new Set();
// broadcast to all connected sockets except one
connectedSockets.broadcast = function(data, except) {
for (let sock of this) {
if (sock !== except) {
sock.write(data);
}
}
}
const server = net.createServer(function(sock){
console.log('new client connected');
connectedSockets.add(sock);
sock.on('end', function() {
connectedSockets.delete(sock);
});
sock.on('data', function(data) {
console.log('Server received');
connectedSockets.broadcast(data, sock);
});
});
I believe you can always keep the socket reference for each client in an array when they established connection to the server. To broadcast, simply loop the array and use perform the write()
var clients = [];
var server = net.createServer(function(sock){
console.log('new client connected');
clients.push(sock);
sock.on('data', function(data) {
console.log('Server received');
for(var i = 0; i < clients.length; i++) clients[i].write('broadcasting..');
});
});
Or if you have the control on both server and client, I think it is better to use websocket or socket.io as it offer broadcast feature.
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.
I have a working socket.io server up and running, and i am trying to implement a server side socket.io client. Below is the code snippet i have been using for testing. The problem with this is that the client outputs the message only once, in this case it receives 'Welcome' only. I have tried sending messages to the private channel, 'message' via browser but it doesn't show any output even though the server can receive and emit the message successfully.
Client
var io = require('socket.io-client');
var socket = io.connect('http://localhost:3000', {'force new connection': true});
socket.on('connect', function(){
socket.on('message', function (data) {
console.log(data);
});
});
Server
var io = require('socket.io').listen(server);
var i=0;
io.sockets.on('connection', function (socket) {
socket.emit('message', { 'msg': 'Welcome'});
socket.on('message', function (from, msg) {
socket.emit('message', { 'msg': 'Hello World - ' + i });
i++;
});
});
Have you tried doing this?
console.log(data.msg);
Can you try changing "socket" to "this":
this.emit('message', { 'msg': 'Hello World - ' + i });
You should emit from client side to server. So server can send the data back to client. I guess this code works fine :-)
Client
var io = require('socket.io-client');
var socket = io.connect('http://localhost:3000', {'force new connection': true});
socket.on('connect', function(){
socket.on('messageRecieved', function (data) {
console.log(data);
});
socket.emit('message','some message');
});
Server
var io = require('socket.io').listen(server);
var i=0;
io.sockets.on('connection', function (socket) {
socket.on('message', function (msg) {
console.log(msg);
socket.emit('messageRecieved', { 'msg': 'Hello World - ' + i });
i++;
});
});
I made a nodejs server wich uses socket.io to establish communication with web client, the server is sending sockets to specific client, the issue is if I have 5 clients connected to the server, the client will receive the sent message 5 times!
here is my code :
var fs = require('fs'),
http = require('http'),
io = require('socket.io'),
qs = require('querystring');
sys = require ('util'),
url = require('url');
var message, AndroidID;
//Traitement Serveur nodejs
var server = http.createServer(function(req, res) {
if(req.method=='POST') {
var body = '';
req.on('data', function (data) {
body += data;
});
req.on('end',function(){
server.emit('sendingData', body);
console.log("Body : " + body);
});
res.write("success");
res.end();
} else {
res.writeHead(200, { 'Content-type': 'text/html'});
res.end(fs.readFileSync(__dirname + '/index.html'));
}
}).listen(8080, function() {
console.log('Listening at: http://localhost:8080');
});
var socket = io.listen(server);
var clients = {};
var compteur = 0;
// Traitement socket.io
socket.on('connection', function (client) {
clients[compteur] = client;
client.emit('firstConnection', client.id, compteur);
console.log('clients : ', clients);
compteur += 1;
client.on('message', function (msg) {
console.log('Message Received: ', msg);
client.broadcast.emit('message', msg);
});
server.on('sendingData', function(data){
message = data.substring(8, data.lastIndexOf('&'));
androidID = data.substr(-1);
console.log('[+] Sending Data : ', message ,' TO : ', parseInt(androidID));
clients[parseInt(androidID)].emit('androidmsg', message);
});
});
The nodejs server is receiving data from a php HTTPClient
You should put server.on('sendingData', function(data){...}); outside socket.on('connection', function (client){...});. This is because the sendingData event is for http server and not socket.io server.
Putting it inside socket.io connection handler makes it repeatedly execute for each connected client to socket.io server
Is it possible to connect to a NodeJS Server from another server? Two NodeJS servers communicating with each other?
//Server Code
var io = require('socket.io').listen(8090);
io.sockets.on('connection', function (socket) {
io.sockets.emit('this', { will: 'be received by everyone'});
socket.on('private message', function (from, msg) {
console.log('I received a private message by ', from, ' saying ', msg);
});
socket.on('disconnect', function () {
io.sockets.emit('user disconnected');
});
});
//Client Code in Server Code. Connecting to another server.
io.connect( "http://192.168.0.104:8091" ); //Connect to another server from this one.
//ETC...
Here's a simple example that creates a server and a client that connects to that server. Remember that what you send has to be a buffer (strings are automatically converted to buffers). The client and server works independently of eachother, so can be put in the same app or on totally different computers.
Server (server.js):
const net = require("net");
// Create a simple server
var server = net.createServer(function (conn) {
console.log("Server: Client connected");
// If connection is closed
conn.on("end", function() {
console.log('Server: Client disconnected');
// Close the server
server.close();
// End the process
process.exit(0);
});
// Handle data from client
conn.on("data", function(data) {
data = JSON.parse(data);
console.log("Response from client: %s", data.response);
});
// Let's response with a hello message
conn.write(
JSON.stringify(
{ response: "Hey there client!" }
)
);
});
// Listen for connections
server.listen(61337, "localhost", function () {
console.log("Server: Listening");
});
Client (client.js):
const net = require("net");
// Create a socket (client) that connects to the server
var socket = new net.Socket();
socket.connect(61337, "localhost", function () {
console.log("Client: Connected to server");
});
// Let's handle the data we get from the server
socket.on("data", function (data) {
data = JSON.parse(data);
console.log("Response from server: %s", data.response);
// Respond back
socket.write(JSON.stringify({ response: "Hey there server!" }));
// Close the connection
socket.end();
});
The conn and socket objects both implement the Stream interface.
Check Substrack's dnode. It auto maps literal objects from the 1st env to the 2nd one. You gain a kind of RPC out of the box. And it works in the browser too...