我正在做一个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')?
问候
以下是时间顺序的事件:
io.on('connection', ...)
事件处理程序。connect
并random
为该套接字上的和事件注册事件处理程序。注意:此插座尚未连接。它正在尝试连接。connection
调用服务器上的事件。console.log('User connected with %s', socket.id);
并User connected with MH0WD_zNzVOzi_6oABAB
在控制台中查看。socket.on('storeClientInfo', ...)
为该新连接的套接字注册事件处理程序。x(socket.id, ...)
,你调用,然后再调用y(...)
哪个输出Show clients:
。y()
完成执行,然后x()
输出x is calling
。connect
事件,你使用发送消息到服务器socket.emit('storeClientInfo', ...)
。storeClientInfo
事件,socket.on('storeClientInfo', ...)
事件处理程序运行,然后输出Thought this would be the first call
。也许你不了解的部分是在客户端中的以下代码:
var socket = io();
是异步的。这只是开始连接过程。返回时套接字尚未连接。socket
你可以使用一个socket.io对象来注册事件处理程序,但该对象尚未连接到服务器。因此,你必须为事件注册一个事件处理程序,connect
以查看事件实际完成连接的时间。