41

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.

Community
  • 1
  • 1
Vipin Kp
  • 422
  • 1
  • 5
  • 8

1 Answers1

62

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);
    });
});
Akash Kumar Verma
  • 3,185
  • 2
  • 16
  • 32
ragamufin
  • 4,113
  • 30
  • 32
  • 3
    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 Dec 06 '13 at 08:19
  • Yes its in the browser – megawac Dec 06 '13 at 08:30
  • 1
    @megawac you need to call the acknowledgement function from the receiving end – robertklep Dec 06 '13 at 08:40
  • 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. – ragamufin Dec 06 '13 at 08:42
  • 2
    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. (/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:335:22) – Vipin Kp Dec 06 '13 at 09:45
  • 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? – Vipin Kp Dec 06 '13 at 10:58
  • 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. – ragamufin Dec 09 '13 at 02:03
  • 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? – Maksim Nesterenko Aug 28 '17 at 15:20
  • 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 – ragamufin Aug 29 '17 at 01:06
  • Question: what happen if for some reason on these exact moment the client is disconnected (loses connection shortly)? – Ali Briceño Jun 28 '19 at 10:20
  • @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 – ragamufin Oct 09 '19 at 21:17
  • WIll it work vice versa too? am trying to do from front end will it work? – Kannan T Jan 09 '23 at 17:08