I just started using socket.io.js and am trying to get a function executed on the server as soon as I send a message to a client. My code is as follows,
server:
server.on('connection', onConnect);
var id = 0;
function onConnect(socket) {
socket.emit('myMsg', {id: ++id}, function () {console.log('id callback on server');});
}
client:
iosocket.on('myMsg', function(data, callback) {
console.log('id:', data.id, callback);
});
However I see that the callback function is displayed as 'undefined' on the client. From what I read on the docs I think this should work (https://github.com/LearnBoost/Socket.IO/wiki/Migrating-0.6-to-0.7+), so could someone please let me know what I am doing wrong here?
I think that the callback must be a function. Try this:
iosocket.on('myMsg', function(data, callback) {
console.log('id:', data.id);
callback();
});
See the acknowledgement section of the following link for an example: http://socket.io/#how-to-use
if you would call callback as a function callback() on the client, it would activate your function on the server side, so it would console.log on your server.
if you just want to send a message from server to client, why make 2 callbacks? you can put it in data: {id:id,something:else).
if you want to log that something on the client;
if(data.something) {
console.log(data.something); //outputs "else"
}