简体   繁体   English

Node.js的“ Emit”和“ On”套接字IO

[英]“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 :) 我刚刚开始尝试node.js,很可能是我弄错了,所以请多多包涵:)

From what I understand, the emit function sends out a custom event and on picks up events and then does something. 据我了解,emit函数会发送一个自定义事件,然后拾取事件,然后执行某些操作。

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. 这表明它应该发出房间事件,并且on函数应该将其拾取。 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.emit()将信息从服务器发送到客户端。

socket.on() receives information sent from the clients to the server. socket.on()接收从客户端发送到服务器的信息。

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. 希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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