[英]How to show real-time server date and time on Nodejs
In Nodejs, how to read the date and time from the server and display in real time on my webpage? 在Node.js中,如何从服务器读取日期和时间并在我的网页上实时显示 ? By using Javascript inside my webpage, it will pick up the date and time of the computer I'm using, not the server.
通过在网页中使用Javascript,它将获取我正在使用的计算机而非服务器的日期和时间。 I want the date and time from server.
我想要来自服务器的日期和时间。
You may simply use socket.io to do it. 您可以简单地使用socket.io来做到这一点。
On server side, create a websocket server, publish the date time every interval (depend on your requirement, seconds, minutes, ...) 在服务器端,创建一个Websocket服务器,每个时间间隔发布日期时间(取决于您的要求,秒,分钟等)
io.on('connection', function (socket) {
socket.emit('datetime', { datetime: new Date().getTime() });
});
On browser side, subscribe the websocket and received the date time from server. 在浏览器端,订阅websocket并从服务器接收日期时间。
var socket = io.connect('http://your-socket-io-server');
socket.on('datetime', function (data) {
$("#clock").text(new Date(data));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.