socket.io: client-side emit callback never fires

后端 未结 3 1839
孤城傲影
孤城傲影 2020-12-28 21:07

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 m

相关标签:
3条回答
  • 2020-12-28 21:19

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

    0 讨论(0)
  • 2020-12-28 21:23

    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>
    
    0 讨论(0)
  • 2020-12-28 21:29

    You can have the callback, but you have to do it a bit differently:


    Server: (app.js)

    var io = require('socket.io')(80);
    
    io.on('connection', function (socket) {
    // please note that server will take 2 data entries as function parameter below
      socket.on('ferret', function (name, fn) {
        fn('woot');
      });
    });
    

    Client (index.html)

    var socket = io(); // TIP: io() with no args does auto-discovery
    socket.on('connect', function () {
    socket.emit('ferret', 'tobi', function (data) {
        console.log(data); // data will be 'woot'
    });
    });
    

    Actaully, socket io also mentions this one; sending-and-getting-data-(acknowledgements)

    0 讨论(0)
提交回复
热议问题