定期在运行时更改HTML主体的内容 – NodeJS

的index.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body></body> </html> 

app.js

我有一个简单的UDP套接字和一个简单的HTTP服务器:

 var socket = require( "dgram" ).createSocket( "udp4" ); socket.on("message", function ( message, requestInfo ) { document.body.innerHTML = message; // which obviously wrong // because the file is running on the client-side // I'm looking for something equivalent }); socket.bind(1247); var http = require('http'), fs = require('fs'); fs.readFile('./index.html', function (err, html) { http.createServer(function(request, response) { response.writeHeader(200, {"Content-Type": "text/html"}); response.write(html); response.end(); }).listen(1247,'xx.xx.xx.xx'); }); 

我正在从其他设备成功并定期(每5秒钟)接收UDP消息。

每次接收到UDP消息时,用户发出第一个请求后,是否有方法可以更改HTML主体的内容?

如果你想要服务器和客户端之间的快速通信,并且你的服务器端处理正在获取套接字上的消息,那么我build议使用socket.io 。

您可以在客户端和服务器之间build立一个Web套接字连接,服务器可以在收到消息时将消息发送给所有客户端。 在你的客户端,你会得到类似于你已经创build的代码。 这是来自socket.io文档的示例代码片段。

 socket.on('new message', function (data) { document.body.innerHTML = data; // do something with the new data }); 

这个答案包含一个很好的socket.io例子。