Socket.io inside Node.js backend routes - javascript

Okay. so im trying to achieve to get socket.io inside all my express routes.
a portion of my code:
var port = process.env.PORT || 3000; // set our port
var server = app.listen(port);
var io = require('socket.io')(server);
app.io = io;
exports.io = io;
then i call it as follows inside other file.
var app = require('../../server');
var io = app.io;
function hijack(user,boatid) {
console.log("????");
console.log(user);
app.io.sockets.emit("myevent",{ test: 22});
var userid = user._id;
console.log(user);
}
module.exports = {
hijack : hijack(app),
};
But, it seems like user parameter inside hijack function now is occupied by the app, and, iff i add an exstra parameter, it still dont know the user parameter, as im calling in the main file by the following:
var ships_model = require('./app/gamemodels/ship_model.js');
ships_model.hijack(req.user, req.body.id).then(function (result) {
res.json(result);
});
Please note: i tried to inject the IO like the following:
var ships_model = require('./app/gamemodels/ship_model.js')(io);
but that just produced errors.
another example:
Is it possible to make a socket emit call within some functions? im only intrested to emit data to the client side.
Or how pusher server sided is working, could that be done with socket too?
the client request is as follows server sided
var bankfactory = require(path.resolve('./modules/articles/server/factory/user_factory.js'));
app.post('/api/bank', function (req, res) {
bankfactory.bank_inn(req.user._id,amount).then( function (bankresult) {
res.json(bankresult);
});
});
bankfactory:
exports.bank_inn = bank_inn;
function bank_inn(playerid,amount) {
if (playerid == 1) {
} else {
// possible to make a emit call to the client here?
//emit("newevent,datahere)
}
}
Note two: I already looked into eventemiters, but with no results.
So, how can i achieve to call socket.emit inside my express routes?
Additional structure code:
main file:
var ships_model = require('./app/gamemodels/ship_model.js');
ships_model.createShipInterface(req.user._id).then(function (response) {
res.json(response);
});
ship_model file have the following structure:
module.exports = {
getShips: getShips(),
createShipInterface : createShipInterface,
allowedLocationsShips : allowedLocationsShips,
startMissionInterface : startMissionInterface,
deligateShipMovements: deligateShipMovements,
upgradeBoat : upgradeBoat,
deletedBoats: deletedBoats,
hijackSession : hijackSession,
boats_to_hijack : boats_to_hijack,
avaliable_boats : avaliable_boats,
createHijackSession : createHijackSession,
public_hijack : public_hijack,
joinHijackSession : joinHijackSession,
leavehijack : leavehijack,
sendMessageToMembers : sendMessageToMembers,
KickMember : KickMember,
togglePublic : togglePublic,
getHangar : getHangar,
hijack : hijack(app),
getHangarSession: getHangarSession,
updateUserLocation : updateUserLocation,
};

As per your comment
So, how can i achieve to call socket.emit inside my express routes?
In our project, what we have done is create a socket server and express server. Thus both express server(server-socket) and browser(client-socket) are clients of socket server.
So whenever express server want to send something to browser, it send data to socket server with the identifier of browser(socket-Id or other unique identifier of client socket) to which we want to send. Then socket server using the identifier send data to the particular browser.

Related

Express-generator, Socket.io Event issuing multiple times

I have create a node app using express generator. I have integrated socket.io in the application. Since express generator has their own way of creating express server i have followed this procedure to successfully integrate the Socket connection with listening server and made the io available throughout the application via res.io instance.
FILE: bin/www
#!/usr/bin/env node
var app = require('../app').app;
var debug = require('debug')('www:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = require('../app').server;
/app.js
//Express handler
var app = express();
// Socket configuration
var server = require('http').Server(app);
var io = require('socket.io')(server);
app.use(function(req, res, next){
res.io = io;
next();
});
...
module.exports = {app: app, server: server};
But the problem is when i m emitting an event as shown below. My client is reading the data multiple times.
routes/index.js
var clients = 0;
var nsp = res.io.of('/default-namespace');
nsp.on('connection', function (socket) {
clients++;
console.log(clients + ' clients connected!');
socket.on('disconnect', (reason) => {
clients--;
console.log(clients + ' clients connected!');
});
nsp.emit("socketToMe", "New User connected. Current clients:"+ clients);
});
My listener has the following code:
home.pug
var socket = io('/default-namespace');
socket.on('socketToMe', function (data) {
$('#data-div').append($('<li>').text(data));
});
Whenever i refresh the browser in another instance like incoginito my main browser is showing multiple events for the data. Like this
New User connected. Current clients:1
New User connected. Current clients:2
New User connected. Current clients:1
New User connected. Current clients:2
New User connected. Current clients:1
New User connected. Current clients:1
Not sure what is wrong. Can anyone help me on this?
Nodejs is event driven.The res object is not a global variable.
Express middleware runs for every request.
var clients = 0;
var nsp = res.io.of('/default-namespace');
nsp.on('connection', function (socket) {
clients++;
console.log(clients + ' clients connected!');
socket.on('disconnect', (reason) => {
clients--;
console.log(clients + ' clients connected!');
});
nsp.emit("socketToMe", "New User connected. Current
clients:"+clients);
});
Let me explain what happens above.A user requests and req handler is fired and you access the res object and you listen for events.
So for each request, you are listening for socket 'connection' event.That means you are setting multiple event listeners with the same name.Every time you make a request you set a new listener.
You are supposed to set only a single 'connection' listener.
This explains emitting the same event multiple times.
app.use(function(req, res, next){
res.io = io;
next();
});
Instead of using the above middleware function,listen directly on io instance

Node.js Socket.io socket.brodcast is undefined

brodcast.emit to send a message to all without socket, and when I do that the node instance crashes and says that socket.brodcast is undefined .
here is my node code:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static('public'));
io.on('connection', function(socket){
socket.on("newChild",childData =>{
var newChildID = mainData.newChild(childData.fatherID,childData.data, childData.type);
socket.emit("newChildID",{ "newId" : newChildID,"old" : childData.localID});
socket.brodcast.emit("newChild",maindata.getDataPoint(newChildID));
});
});
when I emit "newChild" from the client the server crashes and say that socket.brodcast is undefined
The important part is to get socket.brodcast.emit , so do I use the API wrong?
when I googled after it I found this: Send response to all clients except sender (Socket.io)
In this thread I found this example:
socket.on('cursor', function(data) {
socket.broadcast.emit('msg', data);
});
And its seams to be the same as i do.
your code contains a typo for starters...
socket.brodcast.emit("newChild",maindata.getDataPoint(newChildID));
should be
socket.broadcast.emit("newChild",maindata.getDataPoint(newChildID));

Send messages from server to client socket.io

I am trying to send a message from NodeJS server to client using socket.io
However, I found the same practice all over the internet, which is wrapping the emit with io.on('connection', handler) and then making the server listen on a special "channel" event like so:
var io = require('socket.io')();
var socketioJwt = require('socketio-jwt');
var jwtSecret = require('./settings').jwtSecret;
var User = require('./models/users').User;
io.set('authorization', socketioJwt.authorize({
secret: jwtSecret,
handshake: true
}));
var sockets = [];
io.on('connection', function(socket) {
sockets.push(socket);
});
sendLiveUpdates = function(gameSession) {
console.log(sockets);
}
exports.sendLiveUpdates = sendLiveUpdates;
exports.io = io;
My problem is: I want to emit messages outside this on connection wrapper, example from my routes or other scripts. Is it possible?
Thanks.
Yes. You just need to keep a reference to the socket.
// Just an array for sockets... use whatever method you want to reference them
var sockets = [];
io.on('connection', function(socket) {
socket.on('event', function() {
io.emit('another_event', message);
});
// Add the new socket to the array, for messing with later
sockets.push(socket);
});
Then somewhere else in your code...
sockets[0].emit('someEvent');
What I usually do is assign new clients a UUID and add them to an object keyed by this UUID. This comes in handy for logging and what not as well, so I keep a consistent ID everywhere.

socket.io reconnect socket.socket.connect doesn't work

sorry for posting this issue again, but most of the posts related don't answer my question.
i'm having issues to use multiple connections with the socket.io
i don't get the "socket.socket.connect" method to work, yet i get feedbacks from the first connection.
Here's my structure:
var iosocket = null;
var firstconnection = true;
var ip = "http://xxx.xxx.xxx"
var ipPort = 8081
function callSocket() {
iosocket = null;
iosocket = io.connect(ip,{port:ipPort,rememberTransport:true, timeout:1500});
if (firstconnection) {
firstconnection= false;
iosocket = io.connect(ip,{port:ipPort,rememberTransport:true, timeout:1500});
iosocket.on('connect', function () {console.log("hello socket");});
iosocket.on('message', function(message) {});//end of message io.socket
iosocket.on('disconnect', function () {console.log("disconnected");});
} else {
if (iosocket.connected === true) {
console.log("heyhey still connected");
iosocket.disconnect();
}
iosocket.socket.connect(ip,{port:ipPort,rememberTransport:true,timeout:1500});
}
};
it simply doesn't get any feedback from the second connection
i simply solved that IE8 bug by adding
<!DOCTYPE html>
at the top of the html
I think I know why this isn't working. For server-side code, this doesn't seem correct for socket.io. The connect method is used for clients and not servers. I think you are trying to make the server listen on a port. In that case, you should do:
var socket = require('socket.io');
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
var io = socket.listen(server);
io.on('connection', function (client) {
client.on('someEvent', function(someVariables){
//Do something with someVariables when the client emits 'someEvent'
io.emit('anEventToClients', someData);
});
client.on('anotherEvent', function(someMoreVariables){
//Do more things with someMoreVariables when the client emits 'anotherEvent'
io.emit('anotherEventToClients', someMoreData);
});
});
server.listen(8000);

running node.js http server on multiple ports

Please can anybody help me to find out how to get the server socket context in node.js, so that i will come to know request came on which port number on my server.
I can read the server port if i request using http headers but I want it through network and something like socket context which tells request came on which port number.
Here is the sample code:
var http=require('http');
var url = require('url');
var ports = [7006, 7007, 7008, 7009];
var servers = [];
var s;
function reqHandler(req, res) {
var serPort=req.headers.host.split(":");
console.log("PORT:"+serPort[1]);//here i get it using http header.
}
ports.forEach(function(port) {
s = http.createServer(reqHandler);
s.listen(port);
servers.push(s);
});
The req object has a reference to the underlying node socket. You can easily get this information as documented at: http://nodejs.org/api/http.html#http_message_socket and http://nodejs.org/api/net.html#net_socket_remoteaddress
Here is your sample code modified to show the local and remote socket address information.
var http=require('http');
var ports = [7006, 7007, 7008, 7009];
var servers = [];
var s;
function reqHandler(req, res) {
console.log({
remoteAddress: req.socket.remoteAddress,
remotePort: req.socket.remotePort,
localAddress: req.socket.localAddress,
localPort: req.socket.localPort,
});
}
ports.forEach(function(port) {
s = http.createServer(reqHandler);
s.listen(port);
servers.push(s);
});

Categories

Resources