Adam Adam - 5 months ago 29
Node.js Question

Close mubsub client after emitting with socket.io-mongodb-emitter

I'm trying to emit some message into a

socket.io
room using
socket.io-mongodb-emitter
. My problem is that, my script never exists, because it keeps a connection alive to
mongodb
.

Please check my examples below, and give me some advice, how can I make the script close
mongodb
connection and let itself exit.

emitter.js this script emits the message, the client gets it, but the process doesn't exit.

var io = require('socket.io-mongodb-emitter')("mongodb://localhost:27017/test");
io.in('someRoom').emit('someMessage');


emitter-2.js this script exits, but the client never gets the message.

var io = require('socket.io-mongodb-emitter')("mongodb://localhost:27017/test");
io.in('someRoom').emit('someMessage');
io.client.close();


emitter-3.js this one works perfectly, the client gets the message, and the process exits. But
setTimeout
is an extremely bad solution, there must be some proper way to let this process exit by itself.

var io = require('socket.io-mongodb-emitter')("mongodb://localhost:27017/test");
io.in('someRoom').emit('someMessage');
setTimeout(function () {
io.client.close();
},100);

Answer

Maybe use a callback to get an acknowledgement that the client received the message, then call the close function

server:

var message = "hello";
io.in('someRoom').emit('someMessage', message, function(data){
    console.log(data);
    io.client.close();
});

client:

socket.on('someMessage', function(message, callback){
    // do something with message here
    callback('message received');
});