6

我在 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.htmlusers[]

<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>

提前致谢。:)

4

1 回答 1

8

您最好的选择是在播放器连接或断开连接时将用户列表发送回客户端。这是一些示例代码:

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>
于 2013-10-09T08:59:28.767 回答