前端互相控制 sse + nodejs
两个服务,一个长连接对内
前端部分
sse(){
this.source = new EventSource(“http://192.168.22.234:8088/sse”);
this.source.addEventListener(
“open”,
function () {
console.log(“建立连接”);
},
false
);
this.source.addEventListener(
“connecttime”,
function (e) {
console.log(e.data);
console.log(‘connecttime’)
},
false
);
this.source.addEventListener(
“message”,
function (e) {
console.log(e.data);
this.command = e.data
console.log(‘message’)
},
false
);
},
后端部分
const express = require(“express”);
const path = require(“path”);
const app = express();
app.use(express.static(path.join(__dirname)));
app.get("/sse",function (req,res) {
res.append(“Access-Control-Allow-Origin”,"*");
res.append(“Content-Type”,“text/event-stream”);
res.write(“event: connecttime\n”);
res.write(“retry: 10000\n”);
res.write("data: " + (“这是一条命令”) + “\n\n”)
var timer=setInterval(function () {
res.write("data: " + (“这也是一条命令”) + “\n\n”)
},2000);
});
app.listen(8088,()=>{
console.log(‘开启成功’)
});
一个微服务对外,接受其他前端发来的请求,虚暴露地址