gpt4 book ai didi

node.js - nodejs脚本之间的socket.io通信

转载 作者:太空宇宙 更新时间:2023-11-03 23:21:35 24 4
gpt4 key购买 nike

我正在尝试设置一些socket.io通信,我的服务器(app.js)(在树莓派上运行)和网站(public/index.html)之间的通信工作正常。现在我想扩展它,这样当我的 app.js 收到来自 index.html 的调用时,它会将其进一步发送到将在另一个树莓派上运行的另一个 node.js 脚本(bed.js)。我尝试使用npm模块socket.io-client,但这只能明显接收

!编辑!问题已缩小到 setrgb 部分,它不会发出。

!编辑2!当我收到 setRGB 时,我发出 setRGBclient ,但这只能在 bed.js 中接收,而不是在 index.html 中,这就是我的问题,我需要共享连接或强制它到另一个连接,但不知道如何修复它

APP.JS:

let http = require('http').createServer(handler); //require http server, and create server with function handler()
let fs = require('fs'); //require filesystem module
let io = require('socket.io')(http) //require socket.io module and pass the http object (server)
let delay = require('delay');
console.log('Define each color from RGB Strip light.');
http.listen(8080); //listen to port 8080


function handler (req, res) { //create server
fs.readFile(__dirname + '/public/index.html', function(err, data) { //read file index.html in public folder
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'}); //display 404 on error
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'}); //write HTML
res.write(data); //write data from index.html
return res.end();
});
}
io.sockets.on('connection', function (socket) {// WebSocket Connection

socket.on("test", function(){
console.log("sampletext");
});


socket.on("setRGB", function(data){
socket.emit("setRGBClient", data);
console.log(data);
console.log("test");
});
});

bed.js:

let socket = require('socket.io-client')('http://localhost:8080');

let lightstate = false;
let stayOff = false;
let fadeState = false;
console.log("check");
socket.emit("test");
socket.on("setRGBClient" ,function(data) {
console.log(data);
});

最佳答案

我可以只广播setRGBClient。

   socket.broadcast.emit("setRGBClient", data);

关于node.js - nodejs脚本之间的socket.io通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49107857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com