Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Acknowledgment for socket.io custom event

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.

like image 782
Vipin Kp Avatar asked Dec 06 '13 06:12

Vipin Kp


People also ask

How do I send an Acknowledgement in socket IO?

Client Side JavaScript connect('http://localhost:3000'); socket. on('connected', function (data) { //Send message to Server with callback function socket. emit('chat_messsage', {message:"this is message"}, function(response){ console. log(response); //console the Acknowledgment }); });

What is Acknowledgement in socket IO?

Acknowledgements​ In Socket.IO, this feature is named acknowledgements. You can add a callback as the last argument of the emit() , and this callback will be called once the other side acknowledges the event: io. on("connection", (socket) => { socket.

How do I authorize socket IO?

Authorization can be done like so: io. use(function(socket, next) { var handshake = socket. request; next(); });


1 Answers

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);     }); }); 
like image 147
ragamufin Avatar answered Sep 23 '22 01:09

ragamufin