I'm working with mean.js and I need to have some real time features in my app, to accomplish that I'm going to use socket.io library. Here is my idea on how to integrate and still have a good structure in the app.
Mean is using a server.js file, that is the one that do a lot of configurations, so I want to do the following:
// Expose app
exports = module.exports = app;
// Add my reference to the socketServer
var io = require('/socketServer')(app);
The file '/socketServer.js' is going to be my starting point and my configuration point of my socket, could looks something like this:
var http = require('http');
var socketio = require('socket.io');
module.exports = function(express){
var server = http.Server(express);
var io = socketio(server);
io.path('/');
io.on('connect', function(socket){
socket.emit('connected', {msg: 'You are connected now.'});
socket.on('upvote', function(data){
socket.emit('upvoteR', 'newConnected');
socket.broadcast.emit('upvoteR', 'newCOnnected');
});
});
server.listen(8080);
return io;
};
I feel like could be useful for me separate the server default config, of my socket config, and use it file (socketServer.js) as my starting point to develop all my sockets logics injecting the dependencies I want. I don't know if is out there a better approach to this problem, or some structure best practices that I should follow or inconveniences of doing this.
So besides this structure, this are other doubts:
- How to use sockets and express server in the same port? Seems like, with express 4 I'm not able to link the express server with socket, because express 4 server does not inherit any more of httpServer of node.js, so now I have to do a server.listen(socketPort) and if I use the same app.port of mean.js this just is an EADDRINUSE error. Is still possible to have it working in the same port ?
- How to use express session to authenticate each socket connection? if not possible, what's the better approach ? An example or a document reference would be nice for me.
thanks in advance.