谁能帮我解决这个问题吗?我想每次收到消息时都将消息从websocket传递到串口
var firmata = require('firmata');
var board = new firmata.Board('COM4');
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ port: 8081 });
wss.on('connection', function connection(websocket) {
websocket.on('message', function incoming(message) {
board.servoWrite(5, message); //This doesn't work but how do i send?
}
board.on("ready", function() {
board.servoWrite(5, 0); // this works but i need the message from above which I cant access.
});
最佳答案
您应该在 board
准备就绪后添加监听器。
board.on("ready", function() {
wss.on('connection', function connection(websocket) {
websocket.on('message', function incoming(message) {
board.servoWrite(5, message);
});
});
});
要么声明一个变量来告诉您它是否准备好。
var isReady = false;
board.on("ready", function() {
isReady = true;
});
wss.on('connection', function connection(websocket) {
websocket.on('message', function incoming(message) {
if(isReady)
board.servoWrite(5, message);
});
});
关于在nodejs中传递javascript消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30054872/