简体   繁体   中英

Can't update users using socket.io

Im trying to show all the users connected. For first time the event show the only user connected, but if i load a new page with a new nickname, the users are not updated in the first one, and the second page update perfectly, but if i load a third page, the third page updates perfectly and the others not. Only the final page loaded show all the users connected.

Image of my problem

SERVER

var app = require('express')();
var express = require('express');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var nicks = new Array();

app.use(express.static('./public'));

io.sockets.on('connection', function(socket) {

   socket.on('nick', function(data) {

   var nick = data.nick;
        nicks.push(nick);

            socket.emit('users', {
            nicks: nicks
        });
    })

});



app.get('/', function(req, res) {
    res.sendFile(__dirname + '/index.html');
});


http.listen(3000, function() {
    console.log('listening on *:3000');
});

CLIENT

$(document).ready(function() {

    var socket = io();
    var nickname;
    var nicks = new Array();

    nickname = prompt('Write your name:');

    $("#button").on("click", function(event) {

        var nick = nickname;
        socket.emit('nick', {
            nick: nick
        });
    });


    socket.on('users', function(data) {

        nicks = data.nicks;

        for (var i = 0; i < nicks.length; i++) {

            $("#users_connected").append('<li>' + nicks[i] + '</li>');
        }
    });




});

The problem is that your are using socket.emit() from docs:

  • Emits an event to the socket identified by the string name.

Meaning that the only one that is getting the users event is the same that send a nick event.

Yoy must want to use Server.emit() From docs:

  • Emits an event to all connected clients. The following two are

      var io = require('socket.io')(); io.sockets.emit('an event sent to all connected clients'); io.emit('an event sent to all connected clients'); 

That way will allow you to inform all conections about the current users but mostly will fail in your current schema if you dont clear or ignore somehow already added users.

I would prefer to have two events a "new member" and send whole user data not all users and then a "disconected" in order to remove member reference and avoid re printing or validating things.

For more advenced usage you need to check on namespaces. To send events to certain groups of connections.

Check it out ;)

http://socket.io/docs/server-api/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM