Most of the time, my express controller is accessed by routing http requests from angular, allowing me to access the socket in my serverside controllers using req.app.get('socketio')
.
Unfortunately, I have a few functions that are activated by sensors, which communicate without using http. This keeps me from accessing socketio, keeping me from being able to emit. (Note, the server should be able to emit, whether there are clients connected or not).
I'm using MEANJS, so I don't have a terrible lot of control over how things are initialized. The socket configuration is initialized after the modules are loaded. I've tried to set a local variable in my controller from the socket configuration file, but it doesn't seem to persist.
What I've been doing is using angular to make an http call to the controller, which sets a local variable from req.app.get('socketio')
. This is horrible, as that local variable in the server controller isn't set until a client connects and the controller should be able to emit at any time.
config/lib/socketio.js
:
var io = socketio.listen(server);
// Add an event listener to the 'connection' event
io.on('connection', function (socket) {
config.files.server.sockets.forEach(function (socketConfiguration) {
require(path.resolve(socketConfiguration))(io, socket);
});
});
// bind socketio global to allow serverside emission
app.set('socketio', io);
return server;
In modules/server/someModule/sockets/someModule.server.socket.js
:
module.exports = function (io, socket) {
// Emit the status event when a new socket client is connected
io.emit('chatMessage', {...});
// Send a chat messages to all connected sockets when a message is received
socket.on('chatMessage', function (message) {
message.type = 'message';
io.emit('chatMessage', message);
});
Here, I was going to call something like require(myModule).set(io, socket)
but that seemed to create a new instance of the controller.
I don't have access to app
in the controller, but I do in the configuration file, modules/someModule/server/config/someModule.server.config.js
:
module.exports = function (app, db) {
};
Which is empty. I'm stumped.
If another question helps (which was never answered) Socket io emit message to client from express controller method
via stwilbur