Server to Server with Socket.io - node.js

I have two EC2 instances, and I am using socket.io to establish communication between them.
In my First Server I have the following files
server1.js
........
........
var loadData = require("./client/getData");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/', loadData);
var port = Number(process.env.PORT || 5000);
app.listen(port);
var server = require("https").Server(app);
var io = require("socket.io-client");
app.set('socketio', io);
..........
getData.js
......
router.get('/getMetaData', function(req, res){
var io = req.app.get('socketio');
var socket = io.connect('https://172.43.3.2:8080');
socket.on('metaData', function(data){
console.log("MetaData:", data);
res.json(data);
});
});
module.exports = router;
In my Second Server i have the following
server2.js
var express = require('express');
var app = express();
var server = require("https").Server(app);
var io = require("socket.io")(server);
app.get('/', function (req, res) {
res.send('Hello World');
});
var port = Number(process.env.PORT || 5000);
app.listen(port);
var metaData = {
"block1":["id1","id2"]
}
io.on('connection', function(socket){
console.log("Received Connection");
socket.emit('metaData', metaData);
});
console.log("Server Running on:", process.env.PORT);
My request to the route /getMetaData is resulting in "504 Gateway Time-out", I am not sure what I am doing wrong or missing out on

Related

HTML changes not reflecting when running using node and nodemon

I am trying to send my HTML file as a response form my server.js, but it is not adapting to my HTML changed even after restarting the server.
I have also tried nodemon.
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.get('/', function(req, res, next) {
res.sendFile(__dirname + '/public/index.html');
});
app.use(express.static('public'));
app.set('view cache', true);
io.on('connection', function(client) {
console.log('Client connected...');
client.on('join', function(data) {
console.log(data);
});
client.on('messages', function(data){
client.emit('thread', data);
client.broadcast.emit('thread', data);
});
});
server.listen(7777);

NodeJS socket.io in a router page

I have the app.js code:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(socket){
socket.on('newRideAdded', function(exclude){
io.emit('newRideAdded', exclude);
});
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.use(express.static(__dirname + '/public/'));
app.use('/rides', require('./routes/rides'));
app.use('/user', require('./routes/user'));
server.listen("8080", function() {
console.log("Connected to db and listening on port 8080");
});
And I want to move the socket io code to its router's page.
That is the router page:
var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
var db = mongojs("ride4you", []);
router.post('/getRides', function(req, res, next) {
db.rides.find(function(err, docs) {
res.json(docs);
});
});
// rest of the restapi in this page.
// I want socket code to be here
module.exports = router;
As you can see i have each socket emits in each router's page and I already have module.exports in routers page.
How can it be done?
Thanks.
Using Express 4, in your app.js file you can use
app.set('socketio', io);
Then in your router or controller, you can use
router.post('/getRides', function(req, res, next) {
var io = req.app.get('socketio');
io.to(//socket.id//).emit("message", data);
db.rides.find(function(err, docs) {
res.json(docs);
});
};
This is a clean way of passing the reference along.

Unable to post on nodejs in heroku

I have a nodejs app running on Heroku. Here is the server.js file
var express = require('express')
, cors = require('cors')
, app = express();
var http = require('http').Server(app);
var io = require("socket.io").listen(http);
app.use(cors());
require('./modules/routes.js')(app,io);
app.set('port', process.env.PORT || 5000);
app.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
Here is my routes.js
"use strict";
const bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var time = require('express-timestamp');
var Promise = require('promise');
var momentjs = require('moment');
var _ = require('lodash');
var method = routes.prototype;
function routes(app, io) {
app.use(time.init);
app.use(cookieParser());
app.use(session({ secret: 'asdo8rter65edfgfd53wet34634632y4bluaq', resave: true, saveUninitialized: true }));
app.all('/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.use(bodyParser.json());
app.post('/testHeroku', function(req, res) {
console.log(req);
res.write(JSON.stringify({
process: "success"
}));
res.end();
});
}
method.getroutes = function() {
return this;
}
module.exports = routes;
I'm trying to access /testHeroku from an ionic app running in android emulator.
Ionic code:
vm.testHeroku = function(){
console.log('testing heroku');
var testdata = {
url: config.baseURL + 'testHeroku',
dataServer: {
serverTaskRequest: 'getUADSF'
}
}
runajax.runajax_function(testdata, function (testdataResponse) {
if (testdataResponse.process == 'success') {
alert(testdataResponse.process);
}
});
};
Here goes my config.baseURL = abcd-1234.herokuapp.com (This is example for the heroku app url)
I don't receive any return form the http call.
Code for run_ajax service
.service('runajax', ['$http', function ($http) {
this.runajax_function = function (request, callback) {
var url = request.url;
var dataServer = request.dataServer;
// console.log('runajax function called -> ' + url);
// console.log(dataServer);
$http.post(url, dataServer).success(function (data, status, headers, config) {
callback(data);
})
.error(function () {
callback(status);
});
}
}])
I got it working. There was an error with app.set('port', process.env.PORT || 5000); I changed it to var port = process.env.PORT || 8080;

Nodejs : access socket.io instance in express routes files

I would like to be able to emit datas to clients connected to socket.io server from my express routes files.
My app.js looks like this :
var express = require('express');
var app = express();
//routes
require('./routes/test')(app);
// starting http server
var httpd = require('http').createServer(app).listen(8000, function(){
console.log('HTTP server listening on port 8000');
});
var io = require('socket.io').listen(httpd, { log: false });
io.on('connection', function(socket){
socket.join("test");
socket.on('message', function(data){
.....
});
});
module.exports = app;
My test.js file :
module.exports = function(app){
app.post('/test', function(req, res){
.....
//I would like here be able to send to all clients in room "test"
});
};
Simply inject your io object as an argument into the routes module :
app.js :
var express = require('express');
var app = express();
// starting http server
var httpd = require('http').createServer(app).listen(8000, function(){
console.log('HTTP server listening on port 8000');
});
var io = require('socket.io').listen(httpd, { log: false });
io.on('connection', function(socket){
socket.join("test");
socket.on('message', function(data){
.....
});
});
//routes
require('./routes/test')(app,io);
module.exports = app;
test.js :
module.exports = function(app, io){
app.post('/test', function(req, res){
.....
//I would like here be able to send to all clients in room "test"
io.to('test').emit('some event');
});
};

using socket.io in conjunction with express

I am trying to sent a basic message when users connect and disconnect. Later i want to sent parameters back and forth. But with the following code i do not get the messages print out on the server when they connect/disconnect.
When i replace io.on with server.on i can get the message 'User connected' but not user disconnected when i refresh/close the page. This however is buggy, since not everytime i refresh it logs the message and on first time it sometimes log the message multiple times.
server.js
var //io = require('socket.io'),
http = require('http'),
express = require('express');
var PORT = process.env.PORT || 8080,
HOST = process.env.HOST || 'localhost';
var app = express();
app.use(express.static(__dirname + '/views'));
app.get('/', function (req, res) {
res.sendfile(__dirname + 'index.html');
});
server = http.Server(app);
//io = io.listen(server);
var io = require('socket.io')(server);
io.on('connection', function(socket){
console.log('User connected');
io.on('disconnect', function(socket) {
console.log('User Disconnected');
});
});
server.listen(PORT, HOST, null, function() {
console.log('Server listening on port %d in %s mode', this.address().port, app.settings.env);
});
New code:
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server);
var PORT = process.env.PORT || 8080,
HOST = process.env.HOST || 'localhost';
server.listen(PORT);
app.use(express.static(__dirname + '/views')); //need this for my directory structure.
app.get('/', function (req, res) {
res.sendfile(__dirname + 'index.html');
}); //Need this to call my page.
io.on('connection', function( client ){
console.log('Connected');//this does not work.
io.on('disconnect', function( client) {
console.log(client);
});
});
Try reconfiguring your socket, and server instantiation:
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(process.env.PORT || 3000);
io.on('connection', function( client ) {
console.log(client) //this will now work
client.on('disconnect', function( id ) {
console.log('user with ID ' + id + ' has disconnected');
});
});
First of all you need to be sure if you have included the client side socket.io files.
<script src="/socket.io/socket.io.js"></script>
Then you need to initialize the socket connection.
<script>
var socket = io();
</script>
The above changes will be in your index.html file.
Now in server.js file,
io.sockets.on('connection', function(socket) {
console.log("User connected");
socket.on('disconnect', function() {
console.log('Got disconnect!');
});
});

Resources