Nodejs Publish from Client in pub/sub - javascript

I am trying to build a small app in nodejs to publish and subscribe. I am stucked in how I can publish from client side. Here is the code I have.
Here is my server code (server.js)
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app);
app.use(express.bodyParser());
app.get('/', function(req, res) {
res.sendfile(__dirname + '/public/index.html');
});
app.post('/publish/:channel/:event/', function(req, res) {
console.log("**************************************");
var params = req.params;
console.log(req.params);
console.log(req.body);
var data = req.body;
console.log("**************************************");
var result = io.sockets.emit(params.channel,{event:params.event,data:data});
//console.log(result);
console.log("**************************************");
res.sendfile(__dirname + '/public/index.html');
});
//include static files
app.use(express.static(__dirname + '/public'));
server = server.listen(3000);
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (s) {
socket = s
socket.emit('c1', { hello: 'world' });
socket.on('test', function (data) {
socket.emit('c1', { hello: 'world' });
console.log('test');console.log(data);
});
});
And here is client code
var narad = {};
narad.url = 'http://192.168.0.46:3000';
narad.lisentingChannels = {}
var socket = io.connect(narad.url);
function Channel(channelName) {
this.channelName = channelName; //serviceObject is the object of
this.events = {};
};
Channel.prototype.bind = function (event, callback) {
this.events[event] = callback;
};
narad.subscribe = function (channelName) {
var channel = new Channel(channelName)
this.lisentingChannels[channelName] = channel;
socket.on(channelName, this.callbackBuilder(channel))
return this.lisentingChannels[channelName];
}
narad.callbackBuilder = function (channel) {
return function (data) {
var callback = channel.events[data["event"]];
callback(data.data);
}
}

You can use the emit method on both the client and the server websocket connections, taken from Socket.io:
var socket = io.connect(narad.url);
socket.emit('publish', 'message');
Then on your server you listen for the message:
socket.on('publish', function (data) {
// Emit the published message to the subscribers
socket.emit('subscribers', data);
console.log(data);
});
This way you are using the bi-directional communication of websockets without having to use some POST api.

Related

jaeger endpoint isnt recieving data using jaeger Node.js client

Was trying to connect to jaeger using HTTP request using nodejs but the spans are not reaching the jaeger endpoint. please help with this code snippet.,
var initTracer = require('jaeger-client').initTracer;
var config = {
'serviceName': 'servicename1',
'reporter': {
'collectorEndpoint': 'http://jaeger-collector:14268/api/traces',
}
};
var options = {
tags: {
'servicename1': '1.0'
}
};
var tracer = initTracer(config, options);
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.get('/', (req, res) => {
const span = tracer.startSpan('http_request');
res.send('Hello Jaeger');
span.log({'event': 'request_end'});
span.finish();
});
app.get('/', function(req, res) {
res.send("Hello World!");
});
server.listen(3000);
console.log('Express server started on port %s', server.address().port);
Any help would be much appreciated!
Got it! We need to enable sampling strategy to reach the collector endpoint.
var initTracer = require('jaeger-client').initTracer;
var config = {
'serviceName': 'Jaeger_Service',
'reporter': {
'collectorEndpoint': 'http://jaeger-collector:14268/api/traces',
},
'sampler': {
'type': 'const',
'param' : 0.1
}
};
var options = {
'logger': {
'info': function logInfo(msg) {
console.log('INFO ', msg)
},
'error': function logError(msg) {
console.log('ERROR', msg)
}
}
};
var tracer = initTracer(config, options);
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.get('/', (req, res) => {
const span = tracer.startSpan('http_request');
res.send('Hello Jaeger');
span.log({'event': 'request_end'});
span.finish();
});
server.listen(8000);
console.log('Express server started on port %s', server.address().port);

how to set max. of clients of socket io?

to my server are just two clients allowed to connect with. How to set the max of clients on two clients of socket.io?
this is how my server.js looks like:
var path = require('path');
var express = require('express'),
app = express(),
http = require('http'),
socketIo = require('socket.io');
var server = http.createServer(app);
var io = socketIo.listen(server);
server.listen(9000);
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + 'index.html'));
});
app.use(express.static(__dirname + '/'));
io.on('connection', function (socket) {
socket.on('data', function (data) {
socket.broadcast.emit('data', data)
});
socket.on('disconnect', function () {
console.log("disconnect")
});
});
This is untested, but you should be able to check number of users on connection and change it on connect/disconnect.
Here is an example:
const connectedUsers = 0;
const maxUsers = 2;
io.on('connection', function (socket) {
if(connectedUsers + 1 > maxUsers){ // check if the new connection will exceed the max connections allowed
socket.disconnect(); // if so, disconnect the user and exit https://stackoverflow.com/a/5560187/11518920
return;
}
connectedUsers++; // otherwise + 1 to the connectedUsers
socket.on('data', function (data) {
socket.broadcast.emit('data', data)
});
socket.on('disconnect', function () {
connecteUsers--; // on a disconnected decrease the connectedUsers count
console.log("disconnect")
});
});

Only “polling” on socket.io

I have two applications hosted in openshift v2, both have the same code, the first uses Node.js 0.10 and socket.io works perfectly. The second application uses Node.js 8.2.1 but socket.io doesn't work and I get the same error as in these other sites:
Client side receive polling on socket.io
Socket.io cannot connect, resorts to “polling”
Socket.io connection reverts to polling, never fires the 'connection' handler
I tried to make the answers, but without result, if the code is the same in my two applications.. What can be failing? It's necessary to make some changes in the new version of Node.js?
This is the relevant code in my application and information about it:
Both app run perfectly on ports 8080 or 3000.
SERVER
App.js
var fs = require('fs');
var express = require('express');
var app = express();
var server = require('http').Server(app);
var bodyParser = require ('body-parser');
var jwt = require('jsonwebtoken');
var io = require('socket.io')(server);
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
var server_port = process.env.OPENSHIFT_NODEJS_PORT || 3000;
server.listen(server_port, server_ip_address, function () {
console.log( "APP Listening on: " + server_ip_address + ":" + server_port )
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname + '/'));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
console.log('USUARIO CONECTADO');
socket.on('coordenada', function (data) {
io.emit('notificacion', {
Latitud: data.latitudData,
Longitud: data.longitudData,
Nombre: data.name
});
});
});
CLIENT
Controllers.js
app.controller('mapCtrl', function ($scope, NgMap, socket) {
vm = this;
socket.on('notificacion', function(data) {
console.log("coordenada recibida: ", data.Latitud +","+ data.Longitud +" de "+ data.Nombre);
var name = data.Nombre;
vm.transportistas = [
{id:'1', nombre: data.Nombre, posicion:[data.Latitud, data.Longitud]}
];
NgMap.getMap().then(function(map) {
vm.map = map;
google.maps.event.trigger(vm.map, 'resize');
});
});
vm.wayPoints = [
{location: {lat:39.502223, lng: -0.363244}},
];
NgMap.getMap()
.then(function(map) {
vm.map = map;
vm.map.setZoom(6);
vm.map.setCenter(new google.maps.LatLng(40, -4));
});
vm.mostrarDetalles = function(e, transportista) {
vm.transportista = transportista;
vm.map.showInfoWindow('foo-iw', transportista.id);
};
});
factorias.js
app.factory('socket', ['$rootScope', function($rootScope) {
var socket = io.connect();
return {
on: function(eventName, callback){
socket.on(eventName, callback);
},
emit: function(eventName, data) {
socket.emit(eventName, data);
}
};
}]);
And I get this on web console ONLY in the app with Node.js 8.2.1:
GET http://localhost/socket.io/?EIO=3&transport=polling&t=1448850081140-15
GET http://localhost/socket.io/?EIO=3&transport=polling&t=1448850080247-12
GET http://localhost/socket.io/?EIO=3&transport=polling&t=1448850080252-13
etc...
**I'm sorry for my English.

Error: Failed to lookup view 'socket.io' in views directory

I have a problem with my nodejs server. Here is my code
server.js
global.jQuery = global.$ = require('jquery');
var express = require('express'),
path = require('path'),
menu = require("./routes/menu");
var sql = require("mssql");
var http = require("http");
var io2 = require("io");
var app = express();
var serve = http.createServer(app);
var io = require('socket.io')(serve);
var recordset2;
var port = 8080;
app.configure(function () {
app.set('views', __dirname + '/views');
app.set('view engine','jade');
/* app.use(express.favicon());*/
app.use(app.router);
app.use(express.static(path.join(__dirname+'public')));
});
app.get('/:viewname', menu.viewname);
io.on('connection', function (socket) {
socket.on('disconnect', function () {
console.log('user disconnected');
});
socket.on('chat', function (msg) {
socket.broadcast.emit('chat', msg);
});
});
var dbConfig = {
server: "localhost",
database: "MyDatabase",
user: "sa",
password: "sa",
port: 1433
};
function getConnected() {
var conn = new sql.Connection(dbConfig);
conn.connect().then(function () {
var req = new sql.Request(conn);
req.query("SELECT * FROM Countries").then(function (recordset) {
console.log("Recordset:", recordset);
conn.close();
}).catch(function (err) {
console.log("Error!!!!");
console.log(err);
conn.close();
});
}).catch(function (err) {
console.log("Error!!!! ----");
console.log(err);
});
}
getConnected();
app.listen(port);
client's code
var socket = io();
$(function () {
$('#get-button').on('click', function () {
console.log("CLICK");
var msg = "HIIII";
socket.emit('chat', msg);
});
});
I'm trying to make a connection between server and client by socket, but it returns me the following error:
Error: Failed to lookup view 'socket.io' in views directory C:\Radio/views;
at Function.app.render (C:\Radio\node_modules\express\lib\application.js:493:17)
at ServerResponse.res.render (C:\Radio\node_modules\express\lib\response.js:798:7)
at exports.viewname (C:\Radio\routes\menu.js:2:9)
at callbacks (C:\Radio\node_modules\express\lib\router\index.js:164:37)
at param (C:\Radio\node_modules\express\lib\router\index.js:138:11)
at param (C:\Radio\node_modules\express\lib\router\index.js:135:11)
at pass (C:\Radio\node_modules\express\lib\router\index.js:145:5)
at Router._dispatch (C:\Radio\node_modules\express\lib\router\index.js:173:5)
at Object.router (C:\Radio\node_modules\express\lib\router\index.js:33:10)
at next (C:\Radio\node_modules\express\node_modules\connect\lib\proto.js:193:15
Could you help me understand why? I saw there is another similar topics but none of the solutions there helped.
I found a solution two minutes after posting this topic.
global.jQuery = global.$ = require('jquery');
var express = require('express'),
path = require('path'),
menu = require("./routes/menu");
var sql = require("mssql");
var http = require("http");
var io2 = require("io");
var app = express();
var port = 8080;
var ser = app.listen(port); //<-----------This solved my problem.

Encapsulate Socket.io events within Node?

I am looking to separate my Socket.io events/init from my main node server logic. The goal is to not only maintain the Socket.io code, but also maintain any events that I may emit.
I'm a little overwhelmed with understanding the scope of this and the method of encapsulation with Node and was hoping to get some clarification on a better way of doing things.
server.js
//-- Socket.io
var http = require('http').Server(app);
//-- Encapsulate Socket init/events
var io = require('./socket.js').listen(http)
var api = express.Router();
api.route('/users/:user_id')
.put(function(req, res) {
io.dispatch(req.body.event);
}
}
//-- Start Server
http.listen(port);
console.log('Server started on port: ' + port);
io.init(app);
socket.js
'use strict'
var io = require('socket.io');
var ioJwt = require('socketio-jwt');
var clientsConnected = 0;
var ioServer;
exports.listen = function(http, app) {
ioServer = io.listen(http);
return ioServer;
}
exports.init = function(app) {
ioServer.use(ioJwt.authorize({
secret: app.get('secret'),
handshake: true
}));
ioServer.on('connection', function(socket){
connect();
socket.on('error', function(err) {
console.log('Socket.IO error:');
console.log(err);
});
socket.on('disconnect', function(){
disconnect();
});
});
}
function connect() {
clientsConnected++;
console.log('user connected. ' + clientsConnected + ' total.');
}
function disconnect() {
clientsConnected--;
console.log('user disconnected. ' + clientsConnected + ' total.');
}
The minimal communication the two modules need to have is that the http server has to be provided to the sockets module so it can initialize itself properly and the http server must call the sockets module to dispatch appropriately. So, you can pursue modularization that has only those two connections:
server.js
var http = require('http').Server(app);
var dispatch = require('./sockets.js')(http);
var api = express.Router();
api.route('/users/:user_id')
.put(function(req, res) {
dispatch(req.body.event);
}
}
//-- Start Server
http.listen(port);
console.log('Server started on port: ' + port);
sockets.js
'use strict'
var io = require('socket.io');
var ioJwt = require('socketio-jwt');
var clientsConnected = 0;
var ioServer;
module.exports = function(server) {
ioServer = io.listen(server);
ioServer.use(ioJwt.authorize({
secret: app.get('secret'),
handshake: true
}));
ioServer.on('connection', function(socket){
connect();
socket.on('error', function(err) {
console.log('Socket.IO error:');
console.log(err);
});
socket.on('disconnect', function(){
disconnect();
});
// return dispatch function
return function(data) {
io.dispatch(data);
}
}
function connect() {
clientsConnected++;
console.log('user connected. ' + clientsConnected + ' total.');
}
function disconnect() {
clientsConnected--;
console.log('user disconnected. ' + clientsConnected + ' total.');
}

Categories