io.on is not a function

后端 未结 1 1698
情歌与酒
情歌与酒 2020-12-18 03:09

I have this code working for receiving data from my Arduino but I will like to send data back to my Arduino and get a response on my client page. I added a listening functi

相关标签:
1条回答
  • 2020-12-18 04:13

    Your value of io is not what it should be.

    The usual way of doing things is like this:

    var app = require('http').createServer(handler)
    var io = require('socket.io')(app);
    var fs = require('fs');
    
    app.listen(80);
    
    io.on('connect', ...);
    

    But I'm guessing that your value of io is something like this:

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

    That's not the same thing. That's the module handle. But, when you do it this way:

    var io = require('socket.io')(app);
    

    Then, io is a socket.io instance. You can bind listeners to an instance, not to the module handle.


    In every single socket.io server-side example on this doc page, they use one of these forms:

    var io = require('socket.io')(app);
    var io = require('socket.io')(port);
    var io = require('socket.io')(server);
    

    with this:

     io.on('connection', ....);
    

    Nowhere do they do:

    var io = require('socket.io`);
    io.listen(server);
    io.on('connection', ....);
    

    That's just the wrong value for io.


    Long story, shortened, you need to fix what you assign to io to be consistent with the docs. It's the return value from require('socket.io')(app); that gives you a socket.io instance object that you can then set up event handlers on.

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