0

我正在尝试使用node- coap 通过 CoAP 从 IoT 设备传输传感器数据。数据到达 CoAP 服务器时的顺序对我来说很重要。confirmable即使使用请求选项,我也找不到保留数据序列的方法。

我在下面有一个小程序,它显示了我的意思。

如果数据的顺序/顺序很重要,是否可以不使用 CoAP?如果可以,我做错了什么?

'use strict';

const coap = require('coap'),
  cbor = require('cbor'),
  server = coap.createServer();

const sequentialData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let incomingData = [];
let numResponses = sequentialData.length;

server.on('request', (req, res) => {
  const obj = cbor.decodeFirstSync(req.payload);
  incomingData.push(obj.data);
  res.end();
});

server.listen(() => {
  const reqOpts = {
    hostname: 'localhost',
    method: 'POST',
    pathname: '/sequential',
    options: {
      Accept: 'application/cbor'
    }
  };

  sequentialData.forEach((item) => {
    const req = coap.request(reqOpts);
    req.write(cbor.encode({
      data: item
    }));

    req
      .on('response', (res) => {
        res.pipe(process.stdout);
        res.on('end', () => {
          if (--numResponses === 0) {
            console.log(`got data in this order`, incomingData);
            process.exit();
          }
        })
      });

    req.end();
  });
});

上面的节点程序每次运行都会输出不同的顺序。

4

1 回答 1

1

It can't as long you are using UDP as transport.

As per RFC7252:

As CoAP is bound to unreliable transports such as UDP, CoAP messages may arrive out of order, appear duplicated, or go missing without notice. For this reason, CoAP implements a lightweight reliability mechanism, without trying to re-create the full feature set of a transport like TCP. It has the following features:

  • Simple stop-and-wait retransmission reliability with exponential back-off for Confirmable messages.
  • Duplicate detection for both Confirmable and Non-confirmable messages.

https://www.rfc-editor.org/rfc/rfc7252

There are some efforts to make CoAP-over-HTTP in different implementations but it does not belong to CoAP RFC itself.

You may try to dig in this way if you absolutely forced to use CoAP.

于 2017-05-31T15:00:35.753 回答