I develop my first project with nodejs. I use express 3 as framework and socket.io for the client server communication. At the moment I’m trying to create a register form. It works quite well, but I’m not sure how to use socket.io and express together correctly.
I check if the email and the password are valid, if they are not, I would like to push a json object the client.
I use this app route:
app.post('/user', function (req, res) {
var user = new User(req.body.user),
errors;
function userSaveFailed() {
res.render('index');
}
errors = user.validation(req.body.user.confirm);
user.save(errors, function (err) {
if (err) {
// Here I would like to send the Object to the client.
io.sockets.on('connection', function (socket) {
socket.emit('registration', {
errors : errors
});
});
return userSaveFailed();
}
res.render('user/new.jade');
});
});
Well, the client gets the json object, but if another client connects to '/' he also gets the object. I guess I use the socket.io wrong. What’s the common way to use a .emit() in an app route? Is it necessary to use a global authorization for socket.io and express for this test?
one way to do that (if you really want to use socket.io to reply to a post, which you probably shouldn't), is to use one room per user session.
so on the on("connection", ...) do something like so:
socket.join(room) where room is something unique to the session (like the session id for example).
then to send back to only one user:
socketio.of('/')['in'](room).emit(...);, room being that same unique id used above.