socket.io

https://socket.io/

https://socket.io/docs/

emit callback 用法

https://stackoverflow.com/questions/20337832/is-socket-io-emit-callback-appropriate

见老外的疑惑,也是本篇的主题, 为什么服务器端能够直接调用客户端设置的回调函数。

跨进程可以调用函数,真是稀奇。 类似RPC。

官方文档的解释

https://socket.io/docs/#Sending-and-getting-data-acknowledgements

client-代码跟踪

https://github.com/socketio/socket.io-client

以客户端源码为研究对象。

在socket.js文件中,存在emit实现:

如下代码中, 17-20行代码中, 会将callback函数存储到本地的acks数组中, 并将基数记为 packet.id,

然后packet作为数据整体,传送的服务器端。

 Socket.prototype.emit = function (ev) {
if (events.hasOwnProperty(ev)) {
emit.apply(this, arguments);
return this;
} var args = toArray(arguments);
var packet = {
type: (this.flags.binary !== undefined ? this.flags.binary : hasBin(args)) ? parser.BINARY_EVENT : parser.EVENT,
data: args
}; packet.options = {};
packet.options.compress = !this.flags || false !== this.flags.compress; // event ack callback
if ('function' === typeof args[args.length - 1]) {
debug('emitting packet with ack id %d', this.ids);
this.acks[this.ids] = args.pop();
packet.id = this.ids++;
} if (this.connected) {
this.packet(packet);
} else {
this.sendBuffer.push(packet);
} this.flags = {}; return this;
};

服务器端处理完数据后, 调用callback接口后,服务器端调用的接口为包装接口, 包装了数据为packet, 并将id打在packet上, 表示此packet为emit时候的packet对应。

服务器端数据到来后, 根据packet.id定位到 callback函数, 并将packet.data作为参数传递到callback中。

/**
* Called upon a server acknowlegement.
*
* @param {Object} packet
* @api private
*/ Socket.prototype.onack = function (packet) {
var ack = this.acks[packet.id];
if ('function' === typeof ack) {
debug('calling ack %s with %j', packet.id, packet.data);
ack.apply(this, packet.data);
delete this.acks[packet.id];
} else {
debug('bad ack %s', packet.id);
}
};

server-代码跟踪

https://github.com/socketio/socket.io

socket.js中 在onevent中 在数据的args数组之后, 添加了 acknowledge 回调函数

 /**
* Called upon event packet.
*
* @param {Object} packet object
* @api private
*/ Socket.prototype.onevent = function(packet){
var args = packet.data || [];
debug('emitting event %j', args); if (null != packet.id) {
debug('attaching ack callback to event');
args.push(this.ack(packet.id));
} this.dispatch(args);
}; /**
* Produces an ack callback to emit with an event.
*
* @param {Number} id packet id
* @api private
*/ Socket.prototype.ack = function(id){
var self = this;
var sent = false;
return function(){
// prevent double callbacks
if (sent) return;
var args = Array.prototype.slice.call(arguments);
debug('sending ack %j', args); self.packet({
id: id,
type: hasBin(args) ? parser.BINARY_ACK : parser.ACK,
data: args
}); sent = true;
};
};

在 dispatch 负责调用 emitter 原生接口 on 绑定的 事件处理函数:

/**
 * `EventEmitter#emit` reference.
 */

var emit = Emitter.prototype.emit;

/**
* Dispatch incoming event to socket listeners.
*
* @param {Array} event that will get emitted
* @api private
*/ Socket.prototype.dispatch = function(event){
debug('dispatching an event %j', event);
var self = this;
function dispatchSocket(err) {
process.nextTick(function(){
if (err) {
return self.error(err.data || err.message);
}
emit.apply(self, event);
});
}
this.run(event, dispatchSocket);
}; /**
* Sets up socket middleware.
*
* @param {Function} middleware function (event, next)
* @return {Socket} self
* @api public
*/ Socket.prototype.use = function(fn){
this.fns.push(fn);
return this;
}; /**
* Executes the middleware for an incoming event.
*
* @param {Array} event that will get emitted
* @param {Function} last fn call in the middleware
* @api private
*/
Socket.prototype.run = function(event, fn){
var fns = this.fns.slice(0);
if (!fns.length) return fn(null); function run(i){
fns[i](event, function(err){
// upon error, short-circuit
if (err) return fn(err); // if no middleware left, summon callback
if (!fns[i + 1]) return fn(null); // go on to next
run(i + 1);
});
} run(0);
};

至此实现上彻底明了了。

05-11 09:32
查看更多