communicate between modules nodjs - javascript

I have a express module in a file to register username and in another file, socket.io module to create chat. what might be the best way to send username to socket module?
server.js
var express = require('express');
app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var morgan = require('morgan');
var wagner = require('wagner-core');
var bodyParser = require('body-parser');
var port = process.env.PORT || 8080;
var name = [];
app.use(morgan('dev'));
app.use(express.static('public'));
app.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
var dependencies = require("./app/dependencies.js")(wagner);
require('./app/routes.js')(app,wagner);
require('./app/socketio.js')(io,wagner);
http.listen(port,function(){
console.log('listening on *:'+port);
});
./app/routes.js
module.exports = function(app,wagner) {
// api ------------------------------------------------------------------
app.post('/api/user', function(req, res) {
console.log(req.body);
// name.push(req.body.name);
res.json({ message: 'from post' });
wagner.invoke(function (UserName){
UserName = "mjt";
});
});
};
./app/socketio.js
module.exports = function (io,wagner) {
io.on('connection', function(socket){
var userName = wagner.invoke(function(UserName) {
console.log(UserName);
});
console.log('a user connected');
io.emit('user connected', "connected");
socket.on('chat message', function(msg) {
console.log('message: ' + msg);
io.emit('chat message', msg);
});
socket.on('disconnect',function () {
console.log('user disconnect');
io.emit('user disconnected', "disconnected");
});
});
}

Found a way to pass data by making the module singleton, this might not be best solution, but I could achieve what I wanted
./app/socketio.js
var socketio = function () {}
socketio.prototype.users = [];
socketio.prototype.start = function(io){
console.log("from start");
var that = this.users;
var people = {};
io.on('connection', function(socket){
console.log(that);
console.log('a user connected');
io.emit('user connected', "connected");
socket.on('chat message', function(msg) {
console.log('message: ' + msg);
io.emit('chat message', msg);
});
socket.on('disconnect',function () {
console.log('user disconnect');
io.emit('user disconnected', "disconnected");
});
});
}
socketio.prototype.updateUser = function (user) {
console.log(user);
this.users.push(user);
console.log(this.users);
}
module.exports = exports = new socketio();
server.js
var express = require('express');
app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var morgan = require('morgan');
var wagner = require('wagner-core');
var bodyParser = require('body-parser');
var port = process.env.PORT || 8080;
var name = [];
var socketIo = require('./app/socketio.js');
var startio = socketIo.start(io);
socketIo.updateUser("hey");
socketIo.updateUser("there");
app.use(morgan('dev'));
app.use(express.static('public'));
app.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
var dependencies = require("./app/dependencies.js")(wagner);
require('./app/routes.js')(app,wagner,socketIo);
http.listen(port,function(){
console.log('listening on *:'+port);
});
Hope this helps to needed ones like me, please suggest better ways, thanks

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")
});
});

not able to obtain socket connection to node server hosted on heroku

I am trying to send data from one node server to another node server. But when i host the one server on heroku i am not able to obtain a socket connection.
Hope anybody can help. Thanks in advance
server.js
var express = require('express');
var socketIO = require('socket.io');
var path = require('path');
var value = "default";
var PORT = process.env.PORT || 3000;
// var engines = require('consolidate');
// app.set('views', __dirname + '/views');
// app.engine('html', engines.mustache);
// app.set('view engine', 'html');
var app = express();
//var server = app.listen(PORT, () => console.log(`Listening on ${
PORT }`));
var server = require('http').createServer(app);
var io = socketIO(server);
io.on('connection', (socket) => {
console.log('+Client connected successfully+');
socket.on('data', function (data) {
console.log('data from pi' + data);
});
socket.on('disconnect', () => console.log('Client
disconnected'));
});
//console.log(PORT + 'actual listening to'+server.address().port);
server.listen(PORT);
client.js
var io = require('socket.io-client');
var socket = io.connect('https://herokuappname.herokuapp.com/', {
reconnect: true });
console.log('2');
// Add a connect listener
socket.on('connect', function (socket) {
console.log('Connected!');
});

socket.io not working with node server

I'm trying to set up my node server to update all the connected clients with new information in real-time. When I run the code below, the io.sockets.on('connection') callback is fired constantly, flooding the console with the message Client connected!, and the front-end is not being updated from socket.emit(). What am I doing wrong?
app.js
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var models = require('./models.js');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
// Connect to the Mongo database
mongoose.connect('mongodb://localhost/test');
bin/www.js
#!/usr/bin/nodejs
var debug = require('debug')('my-application');
var app = require('../app');
app.set('port', process.env.PORT || 3000);
var io = require('socket.io').listen(app.listen(app.get('port')));
io.sockets.on('connection', function(socket) {
console.log('Client connected!');
socket.on('message', function(data) {
console.log('Sending update!');
socket.emit('update', 'Working!');
});
});
public/javascripts/update.js
var socket = io.connect('http://' + document.location.hostname + ':3000/');
socket.on('connect', function() {
console.log('Socket connected!');
socket.emit('message', 'Message from client');
});
socket.on('update', function(data) {
alert(data);
});
And when I end the npm process, the client begins to log
http://<ip>:3000/socket.io/?EIO=2&transport=polling&t=1498772846992-691 net::ERR_CONNECTION_REFUSED
I've read posts about the express router messing with the socket requests but I can't seem to get it working no matter what I try.
Can you try this setup?
EDITED:
app.js:
var express = require('express');
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'pug');
app.get('/', function (req, res) {
res.render('index');
});
module.exports = app;
bin/www.js:
var app = require('../app');
var http = require('http');
var server = http.createServer(app);
server.listen(process.env.PORT || '3000', function () {
console.log('server listens on port 3000');
});
var io = require('socket.io')(http);
io.listen(server);
io.on('connection', function(socket) {
console.log('Client connected!');
socket.on('message', function (data) {
console.log('Sending update!');
socket.emit('update', 'Working!');
});
});
index.pug (or jade, they say jade is obsolete):
doctype html
html
body
h1 Testing socket.io
h3#status not connected
br
p#update update:&nbsp
script(src="/socket.io/socket.io.js")
script.
var socket = io();
socket.on('connect', function() {
document.getElementById("status").innerHTML = "connected";
socket.emit('message', 'Hello!');
});
socket.on('update', function (data) {
document.getElementById("update").innerHTML += data;
});
Calling app.listen (where app is the result of invoking express()) returns an HTTPServer, which can be used to setup the socket connection:
var server = app.listen(port);
var io = socket(server);
without manually running your solution, I'd guess that because you're creating a new HTTPServer to be feed into the socket, it's somehow getting hung in a loop.

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.

Categories