I've got an application which consists of three different parts.
There is a presenter website that shows some information which is delivered through a websocket with socket.io.
I've got a node.js server which takes the data from different users and sends it to the presenter to display it.
There is a small website used by the common users that generates the data shown by the presenter.
All communication between user <--> server
and server <--> presenter
is handled with socket.io 1.0.6.
Here is how it should work:
The presenter is registerd at the server
An user is registered at the server
The server sends a notification to the presenter, that a new user has registered
Another user is registered at the server
Again should the server send a notification to the presenter
So, I got the problem at point 5. Everything before works just fine. I checked the disconnect
event and it gets fired after the first socket.emit(..)
to the presenter.
Why is the connection closed and how can I keep it alive?
Following is some code which reproduces the problem for me:
var io = require('socket.io').listen(8000),
us = require('underscore');
var users = [];
io.sockets.on('connection', function (socket) {
socket.on('newUser', function(data) {
users.push({
name: data.name,
gender: data.gender,
role: data.role,
socket: socket
});
if(data.role === "user") {
sendToAll(getUsersByRole("presenter"), "registerUser", {
name: data.name,
gender: data.gender,
role: data.role
});
}
});
socket.on('disconnect', function(reason){
console.log("Disconnected: " + reason);
});
});
function getUsersByRole(role) {
var roleUsers = [];
for (var i = users.length - 1; i >= 0; i--) {
if(users[i].role === role){
roleUsers.push(users[i]);
}
}
return roleUsers;
}
function sendToAll(users, name, msg) {
us.each(users, function(user) {
user.socket.emit(name, msg);
user.socket.emit(name, { name:"test", gender: "f", role: "user" }); //this second emit is not sent. Why?
});
}