I wrote this code basically:
socket.on('disconnect', function (socket) {
var remove_id = usersonline.indexOf(socket.user);
usersonline.splice(remove_id, 1);
socket.broadcast.emit('usergone', {
'left_user' : socket.username
});
});
that's server side, here is client side:
socket.on('usergone', function(data){
var old_user = data['left_user'];
console.log(old_user);
$(old_user).remove();
});
It doesn't go off however, I tested it doesn't execute client side code which I guess means it doesn't get to it.
Any ideas?
Basically I am building chat application. So far it works fine, as user joins they get added to users online list etc... but when user leaves - I cannot find way to tell all other online users that user has left and remove him from users online list/tab.
I am creating socket connection with following:
var http = require('http'),
express = require('express'),
app = express(),
jade = require('jade'),
io = require('socket.io'),
server = http.createServer(app);
io = io.listen(server);
server.listen(3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set("view options", { layout: false });
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.render('home.jade');
});
var usersonline = [];
io.sockets.on('connection', function (socket) {
functions here.
});
When user connects: their username is added to usersonline, then it broadcasts to my script.js (which is client side). It parses the array of usersonline and loads list of users in chatroom for client that just joined. It also sends just joined users username and tells others that he is there now, and he is added to list of online users.
socket.username = data;
usersonline.push(data);
socket.emit('loadusers', usersonline);
socket.broadcast.emit('newuser', {
'username' : data
});
All works fine. Except I cannot come up with way to notify all other users when user has left. I thought I can easily: on disconnect - broadcast to all others that [username] has left. My users online list works by appending the current list and adding new user.
socket.on('newuser', function(data){
$('#chatUsers').append('<div class="user" id="'+data['username']+'">'+data['username']+'</div');
});
so when user leaves I thought I can easily just remove that div and user will dissapear from list of online users dynamically. But this doesn't work. Need an alternative way.