简体   繁体   中英

“Emit” and “On” socket IO, Node.js

I am just starting to try out node.js and its very likely that I am mistaken so please bear with me :)

From what I understand, the emit function sends out a custom event and on picks up events and then does something.

Here is of bit of the code from the book I'm learning from.

socket.on('rooms', function(rooms) {
    console.log("room received");
    $('#room-list').empty();
    for(var room in rooms) {
        room = room.substring(1, room.length);
        if (room != '') {
            $('#room-list').append(divEscapedContentElement(room));
        }
    }
    $('#room-list div').click(function() {
        chatApp.processCommand('/join ' + $(this).text());
        $('#send-message').focus();
    });
});

setInterval(function() {
    socket.emit('rooms');
    console.log("room emitted");
}, 1000);

It is logging "room emitted" in the console every second however, it isn't logging "room received"

This shows that it should be emitting the rooms event and the on function should be picking it up. However for some reason it isn't.

Is there something I'm doing wrong???

socket.emit() sends information from the server to the client(s).

socket.on() receives information sent from the clients to the server.

You can't emit a message from the server to the server unless the server is connected as a client to itself.

Hopefully this was helpful.

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