shuky chen
shuky chen

Reputation: 21

Data sent evet on socket.io nodejs

I have a nodejs server that sends a huge amount of data to a web client over web socket (using socket.io and socket.io-client).

I am trying to optimize my system when dealing with a low-bandwidth client, and my server produce data faster then what my client is capable of receiving(due to its low-bandwidth link).

In order to optimize my system I need to know whether my client has read the previous message (and then I can saftly send another one) or it didnt (and then I would aggregate my messages until it will).

Does socket.io or nodejs has any API that allows me to know this information?

P.S. I already tried to listen to 'drain' event of engine.io but its too high level (it doesnt tell if the client read my message).

Upvotes: 0

Views: 284

Answers (1)

Vishnu Shekhawat
Vishnu Shekhawat

Reputation: 1265

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

Upvotes: 3

Related Questions