io.on不是函数 [英] io.on is not a function

查看:112
本文介绍了io.on不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码可用于从Arduino接收数据,但我想将数据发送回Arduino并在客户端页面上获得响应.我添加了侦听功能,但是从客户端页面发送数据时却始终显示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);

        });
    });
});

推荐答案

您的io值不是应该的值.

通常的做事方式是这样的:

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', ...);

但是我猜你的io值是这样的:

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

然后,io是一个socket.io实例.您可以将侦听器绑定到实例,而不是模块句柄.

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

此文档页面上的每个socket.io服务器端示例中,他们都使用其中之一形式:

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

与此:

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

他们无处可做:

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

这只是io的错误值.

长话短说,您需要修正分配给io的内容以与文档一致. require('socket.io')(app);的返回值为您提供了一个socket.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.

这篇关于io.on不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆