[Socket.io/Node.js]Retrieving连接用户到客户端的列表

时间:2013-10-09 08:51:58

标签: javascript node.js socket.io

我在socket.io客户端遇到问题,因为我无法显示客户端中所有用户的用户名列表。我是socket.io的新手,我知道如何在服务器端编码。我在客户端编程时遇到困难。我只想在client.html <div id="users"></div>中显示已关联的用户用户名。

以下是 server.js

中的部分代码
var users = [];

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[user] = user;
        console.log(users);
    });

    socket.on('disconnect', function () {
        console.log('User: ' + users[socket.user] + ' has disconnected');
        delete users[socket.user];
        console.log(users)
    });

    socket.on('update', function () {
        users[user] = user;
        console.log('Current users: ', users);
    });
});
});

以下是我的简单 client.html ,用于将用户名插入数组users[]

<html>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
    var socket = io.connect('http://localhost:8080');

socket.on('connect', function(){
        socket.emit('adduser', prompt("What's your name?"));

</script>
<div style="float:left;width:150px;border-right:2px solid black;height:510px;padding:10px;overflow:scroll-y;text-align:center;">
    <b>Users</b>
    <div id="users"></div>
</div>
</html>

提前致谢。 :)

1 个答案:

答案 0 :(得分:6)

最好的办法是在玩家连接或断开连接时向用户列表发回用户列表。以下是一些示例代码:

var users = [];

app.get('/', function (req, res) {

res.sendfile(__dirname + '/test.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);
    }

});

在您的客户端代码中:

<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
    var socket = io.connect('http://localhost:8080');

    socket.on('connect', function (){
        socket.emit('adduser', prompt("What's your name?"));
    });

    var userList = [];

    socket.on('update', function (users){
        userList = users;
        $('#user').empty();
        for(var i=0; i<userList.length; i++) {
            $('#user').append("<h1>" + userList[i] + "</h1>"); 
        }
    });
</script>
<div style="float:left;width:100px;border-right:1px solid black;height:300px;padding:10px;overflow:scroll-y;">
    <b>Users</b>
    <div id="users">
        <p id="user"></p>
    </div>
</div>