用户断开连接时无法更新用户列表,仅在用户连接时更新,我的代码有什么问题? 如果我有用户A,B,C和C离开房间,那么列表仍然是用户A,B,C,并且必须只是A和B.
SERVER
var app = require('express')();
var express = require('express');
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static('./public'));
var users = [];
var nicks = new Array();
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.on('adduser', function (user) {
socket.user = user;
users.push(user);
updateClients();
});
socket.on('disconnect', function () {
for(var i=0; i<users.length; i++) {
if(users[i] == socket.user) {
delete users[users[i]];
}
}
updateClients();
});
function updateClients() {
io.sockets.emit('update', users);
}
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
客户端
$(document).ready(function() {
var socket = io();
socket.on('connect', function (){
socket.emit('adduser', prompt("What's your name?"));
});
var userList = [];
socket.on('update', function (users){
userList = users;
$( "h1" ).remove();
for(var i=0; i<userList.length; i++) {
$('#wrap').append("<h1>" + userList[i] + "</h1>");
}
});
});