在socket.io确认示例中,我们看到客户端的发送/发送与服务器的响应一起被回调。反向是否提供相同的功能-即服务器如何确认从服务器发送/发送的客户端接收?即使只是表示接收成功,也可以有一个发送/发送回调。在任何地方都没有看到此功能的文档...谢谢!
查看socket.io源代码,我发现服务器发送的消息确实支持ACK(但不支持广播!)(socket.io/lib/socket.js的第115-123行):
if ('function' == typeof args[args.length - 1]) {
if (this._rooms || (this.flags && this.flags.broadcast)) {
throw new Error('Callbacks are not supported when broadcasting');
}
debug('emitting packet with ack id %d', this.nsp.ids);
this.acks[this.nsp.ids] = args.pop();
packet.id = this.nsp.ids++;
}
Run Code Online (Sandbox Code Playgroud)
ack 应该如何工作的示例(未测试):
// server-side:
io.on('msg', (data, ackCallback) => {
console.log('data from client', data);
ackCallback('roger roger');
});
// client-side:
socket.emit('msg', someData, (answer) => {
console.log('server\'s acknowledgement:', answer);
});
Run Code Online (Sandbox Code Playgroud)