Warm tip: This article is reproduced from serverfault.com, please click

node.js-Socket.io的调用顺序不清楚

(node.js - Socket.io sequence of calls unclear)

发布于 2020-11-30 01:14:02

我正在做一个socket.io,Node项目,我不理解调用函数的顺序。我有以下服务器代码:

//Socket setup
var io = require('socket.io')(http);
var c= [];

//functions
function y(clientid){
    console.log('Show clients: '+c)
}

var x = function(socketid, fn) {
    var customid = y(socketid)
    console.log('x is calling');
    fn(customid);
};


io.on('connection', (socket) => {
    console.log('User connected with %s', socket.id);

    socket.on('storeClientInfo', function (data) {
        console.log('Thought this would be the first call')
        //clients.push here
    });
    
    
    x(socket.id, function(socketid, ) {
        socket.emit('random', {
            test1: 'test1',
            test2: 'test1'
        });

    });
});

我为客户提供的代码是:

var socket = io();

        socket.on('connect', function () {
            socket.emit('storeClientInfo', { customId:Math.floor(Math.random() * 100 + 1 )});
        });

        socket.on('random', function (message) {
              //display message here
        });

我的控制台日志输出:


User connected with MH0WD_zNzVOzi_6oABAB
Show clients: 
x is calling
Thought this would be the first call

现在我的问题是:为什么一开始该方法被称为而不是socket.on('storeClientInfo')?

问候

Questioner
Botsud
Viewed
0
jfriend00 2020-11-30 10:52:47

以下是时间顺序的事件:

  1. 你的套接字设置代码将运行并注册io.on('connection', ...)事件处理程序。
  2. 你的客户端尝试建立连接,connectrandom为该套接字上事件注册事件处理程序注意:此插座尚未连接。它正在尝试连接。
  3. 服务器接收连接,并connection调用服务器上的事件。
  4. 你输出的结果,console.log('User connected with %s', socket.id);User connected with MH0WD_zNzVOzi_6oABAB在控制台中查看
  5. 然后,你socket.on('storeClientInfo', ...)为该新连接的套接字注册事件处理程序。
  6. 然后x(socket.id, ...)你调用,然后再调用y(...)哪个输出Show clients:
  7. y()完成执行,然后x()输出x is calling
  8. 至此,服务器端连接逻辑完成。
  9. 客户端随后接收到该connect事件,你使用发送消息到服务器socket.emit('storeClientInfo', ...)
  10. 你的服务器收到storeClientInfo事件,socket.on('storeClientInfo', ...)事件处理程序运行,然后输出Thought this would be the first call

也许你不了解的部分是在客户端中的以下代码:

var socket = io();

是异步的。这只是开始连接过程。返回时套接字尚未连接。socket你可以使用一个socket.io对象来注册事件处理程序,但该对象尚未连接到服务器。因此,你必须为事件注册一个事件处理程序,connect以查看事件实际完成连接的时间。