Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.io: client-side emit callback never fires

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>
like image 917
jdc0589 Avatar asked Jul 20 '11 02:07

jdc0589


1 Answers

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>
like image 57
Lime Avatar answered Oct 13 '22 21:10

Lime