socket.io: client-side emit callback never fires


Question

Messing around with socket.io just for proof of concept, everthing is working great so far except I can't get my emit callback to work on the client side. I've got to be missing something stupid here, but documentation is not killer at the moment. The server picks up the "getSomeData" event just fine, no errors anywhere.

From what I could tell in the client socket.io source, it checks if the last argument to emit is a function and always uses it as a callback, but debugging any deeper than that was problematic for me.

I feel like I have to be missing some core concept here..Is this not what this.send(..) is supposed to do? I could find only 1 useage in the example apps, and none where the client side code for that event emission was available.

Update: just to be clear, I am in fact intentionally emitting the event client side. The purpose of this was to see if socket.io could be used to allow clients to pull data on request in addition to receiving pushes.

server:

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
    socket.on("getSomeData", function() {
        this.send({data: "some random data"});
    });
});

client: (console.log never happens)

<script type="text/javascript" src="http://localhost/socket.io/socket.io.js"></script>
<script type="text/javascript">
  var socket = io.connect('http://localhost');
  socket.emit("getSomeData", function(data) {
      console.log(data);
  });
</script>
1
10
7/20/2011 4:04:18 AM

Accepted Answer

It looks like you have some logic switched around, try...

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
    socket.emit("getSomeData",{data: "some random data"});
});

and client...

<script src="http://localhost/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on("getSomeData", function(data) {
      console.log(data);
  });
</script>

EDIT:

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
    socket.on("getSomeData", function(name,fn) {
        fn({data: "some random data"});
    });
});

Client

<script src="http://localhost/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.emit("getSomeData", function(data) {
      console.log(data);
  });
</script>
22
7/20/2011 4:49:06 AM

In Liam William's answer, I found it was necessary to send the callback (or acknowledgement function) as the third argument on the client emit:

Client:

<script src="http://localhost/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.emit("getSomeData", null, function(data) {
    console.log(data);
});


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon