io.on 不是函数 [英] io.on is not a function
问题描述
我有这段代码用于从我的 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
的价值不是它应该的.
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', ...);
但我猜你的 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屋!