使用 Node.js 和 COAP 协议构建物联网应用程序 - 实时时间数据传输示例
以下是使用 Node.js 实现物联网应用程序的代码,使用 COAP 通信协议,服务端监听客户端的请求,每隔一毫秒发送当前时间的字符串。当服务器有新的响应数据时,客户端将其打印到控制台上。
服务端代码:
const coap = require('coap');
const server = coap.createServer();
server.on('request', function(req, res) {
console.log('Received request: ' + req.method + ' ' + req.url);
setInterval(() => {
res.end(new Date().toString());
}, 1);
});
server.listen(function() {
console.log('Server started');
});
客户端代码:
const coap = require('coap');
const client = coap.request('coap://localhost');
client.on('response', function(res) {
console.log('Received response: ' + res.payload.toString());
});
client.end();
运行以上代码,客户端会不断输出当前时间的字符串。可以使用命令行工具观察输出结果:
$ node client.js
Received response: Thu Oct 07 2021 16:41:00 GMT-0700 (Pacific Daylight Time)
Received response: Thu Oct 07 2021 16:41:01 GMT-0700 (Pacific Daylight Time)
Received response: Thu Oct 07 2021 16:41:02 GMT-0700 (Pacific Daylight Time)
Received response: Thu Oct 07 2021 16:41:03 GMT-0700 (Pacific Daylight Time)
...
原文地址: https://www.cveoy.top/t/topic/m8WH 著作权归作者所有。请勿转载和采集!