Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
571 views
in Technique[技术] by (71.8m points)

javascript - io.on is not a function

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 function but I keep getting io.on is not a function when I send data from my client page.

test.js

io.listen(app.listen(3000)).on('connection', function (client) {

    // store client into array
    clients.push(client);

    // on disconnect
    client.on('disconnect', function() {

        // remove client from array
        clients.splice(clients.indexOf(client), 1);


    });

    // I added this to listen for event from my chart.JS

    io.on('connection', function(socket){

        socket.on('LED on', function (data) {
            console.log(data);

        });
        socket.on('LED off', function (data) {
            console.log(data);

        });
    });
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...