Files
coapwithudp/nodejs/client.js
Md Imran Hossain 137b9d9547 Add CoAP-over-UDP hello server in Rust
A minimal CoAP (RFC 7252) server built on coap-lite for message encoding
and a tokio UdpSocket for transport. The socket, read loop and routing are
kept in src/main.rs rather than behind a framework.

Routes:
  GET  /hello[?name=X]  -> 2.05 "Hello, X!" (defaults to World)
  POST /hello           -> 2.01, name from a raw text or JSON body
  GET  /health          -> 2.05 status + uptime

Unknown paths return 4.04, known paths with the wrong method 4.05.

Includes a CLI client (src/bin/client.rs) for smoke tests and unit tests
covering the greeting, payload parsing and query decoding. Verified against
node-coap as an independent implementation to confirm wire compatibility.

The earlier Node.js prototype is kept under nodejs/ for reference.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 10:28:24 +06:00

33 lines
766 B
JavaScript

'use strict';
// Tiny CLI client:
// node client.js get /hello?name=Imran
// node client.js post /hello Imran
// node client.js get /health
const coap = require('coap');
const [, , methodArg = 'get', pathArg = '/hello', payload] = process.argv;
const req = coap.request({
host: process.env.COAP_HOST || 'localhost',
port: Number(process.env.COAP_PORT) || 5683,
pathname: pathArg.split('?')[0],
query: pathArg.split('?')[1] || '',
method: methodArg.toUpperCase(),
confirmable: true,
});
req.on('response', (res) => {
console.log(`<- ${res.code} ${res.payload.toString()}`);
process.exit(0);
});
req.on('error', (err) => {
console.error('request failed:', err.message);
process.exit(1);
});
if (payload) req.write(payload);
req.end();