很多摆弄周围,寻找做到这一点的最好办法后,我绊倒的server sent events概念。这是(以一种非常简单的方式解释)像socket.io,但只有一种方法 - 顾名思义 - 从服务器到客户端。 SSE通过HTTP完全过滤,因此不需要Websocket。
中间件配置:
module.exports = function (req, res, next) {
res.sseSetup = function() {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
res.connection.setTimeout(10800000);
};
res.sseSend = function(data) {
res.write("data: " + JSON.stringify(data) + "\n\n");
};
next();
}
现在有了明确注册您的中间件(通常在app.js):
app.use(require('./middlewares/sse'));
,并添加必要的路由处理程序:
router.get('/time', function(req, res) {
res.sseSetup();
setInterval(function() {
// create your time object - here: {time: 11:30:01}
res.sseSend(timeObject);
},1000);
});
客户端代码:
<script>
if(!!window.EventSource) {
var timeSource = new EventSource('/time');
timeSource.addEventListener('message', function(event) {
var data = JSON.parse(event.data);
$('.time').text(data.time);
}, false);
}
else {
console.log("[ERROR](server) Your browser does not support SSE");
}
在这种情况下的数据对象看起来像这样:
{
time: '11:30:01'
}
和随意可以扩展/调整。
干杯!
从来没有与汉德尔的工作,但你不能在那里的JavaScript。 Settimeout或setInterval将完成作业 –
@sacDahal:但是使用setTimeout或setInterval只能在客户端工作,对吧?但是如果用户的机器设置了错误的时间,则错误的时间将显示在页面上 – Beejay