Acknowledgment for socket.io custom event

26,589

The third argument to the emit method accepts a callback that will be passed to the server so that you can call in acknowledgement with any data you wish. It's actually really convenient and saves the effort of having paired call-response events.

I'm updating my answer with some code that I just tested.

First on the server side:

   io.sockets.on('connection', function (sock) {

    console.log('Connected client');
    sock.emit('connected', {
        connected: 'Yay!'
    });

    // the client passes 'callback' as a function. When we invoke the callback on the server
    // the code on the client side will run
    sock.on('testmessage', function (data, callback) {
        console.log('Socket (server-side): received message:', data);
        var responseData = {
            string1: 'I like ',
            string2: 'bananas ',
            string3: ' dude!'
        };
        //console.log('connection data:', evData);
        callback(responseData);
    });
});

On the client side:

console.log('starting connection...');
var socket = io.connect('http://localhost:3000');
socket.on('error', function (evData) {
    console.error('Connection Error:', evData);
});
// 'connected' is our custom message that let's us know the user is connected
socket.on('connected', function (data) {
    console.log('Socket connected (client side):', data);

    // Now that we are connected let's send our test call with callback
    socket.emit('testmessage', {
        payload: 'let us see if this worketh'
    }, function (responseData) {
        console.log('Callback called with data:', responseData);
    });
});
Share:
26,589
Vipin Kp
Author by

Vipin Kp

Updated on June 07, 2021

Comments

  • Vipin Kp
    Vipin Kp almost 3 years

    I am looking for a method to acknowledge a socket.emit call.

    socket.emit('message', msg);
    

    I have seen a mechanism where the receiver would send another custom event as an acknowledgement, but this would add thousands of transports in my chat application. Please advice an efficient method.

  • megawac
    megawac over 10 years
    I can't verify this a.socket.emit("echo", {payload:'test'}, function(){console.log("success")}) never gets logged but I receive the echo (9.16)
  • megawac
    megawac over 10 years
    Yes its in the browser
  • robertklep
    robertklep over 10 years
    @megawac you need to call the acknowledgement function from the receiving end
  • ragamufin
    ragamufin over 10 years
    and also keep in mind that the you the 'connect' event does NOT allow you to acknowledge it. In that case you do need a paired response event that you emit yourself.
  • Vipin Kp
    Vipin Kp over 10 years
    socket.on('adminMessageClient', function(data, userID, callback) { callback("Ack response from server"); }); This statement in server is throwing error callback("Ack response from server"); ^ TypeError: undefined is not a function at Socket.<anonymous> (/var/node_server/newChatServer.js:141:3) at Socket.EventEmitter.emit [as $emit] (events.js:101:17) at SocketNamespace.handlePacket (/var/node_server/node_modules/socket.io/lib/namespace.js:33‌​5:22)
  • Vipin Kp
    Vipin Kp over 10 years
    Can I pass this callback to another method can call if from the new method? I tried passing callback as I to with normal variables, but not working, any clue?
  • ragamufin
    ragamufin over 10 years
    Sure, it's a function like any other so you can call as many things as you'd like and pass the callback around. I also do that to go and fetch things from the database and so on and then in the end I call the callback.
  • Maksim Nesterenko
    Maksim Nesterenko over 6 years
    Is there some convention for acknowledge function argument? Like null if ok (nodejs callback convention - first argument always should be err, but here just one...) or something else?
  • ragamufin
    ragamufin over 6 years
    There is no convention that I know of but you are free to use say the nodejs convention if you like. In the example where there is callback(responseData); you could pass two arguments instead of one and do it that way as a convention you implement yourself
  • Ali Briceño
    Ali Briceño almost 5 years
    Question: what happen if for some reason on these exact moment the client is disconnected (loses connection shortly)?
  • ragamufin
    ragamufin over 4 years
    @AliBriceño I'm not sure but I think things are setup to handle this gracefully, if either side loses connection I think both server and client will get an event and it's up to you to test this eventuality and handle it