Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an acknowledgment on server send/emit

Tags:

socket.io

In the socket.io acknowledgement example we see a client's send/emit being called back with the server's response. Is the same functionality available in the reverse direction - i.e. how does the server confirm client reception for a send/emit from the server? It would be nice to have a send/emit callback even just to indicate reception success. Didn't see this functionality documented anywhere... Thanks!

like image 558
Mark Avatar asked Nov 04 '22 04:11

Mark


1 Answers

Looking in the socket.io source I found that indeed ACKs are supported for server-sent messages (but not in broadcasts!) (lines 115-123 of socket.io/lib/socket.js):

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++;
}

An example of how the ack should work (not tested):

// 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);
});
like image 76
klh Avatar answered Nov 30 '22 23:11

klh