nats.ws example
HTML
<!doctype html>
<html>
<head>
<script defer type="module">
// ES6 modules can be natively used by set the script type
// to "module". Now we can use native imports.
import {
connect,
StringCodec,
} from "https://cdn.jsdelivr.net/npm/[email protected]/esm/nats.js";
// Initialize a string codec for encoding and decoding message data.
// This is because NATS message data are just byte arrays, so proper
// encoding and decoding needs to be performed when using the working
// with the message data.
// See also JSONCodec.
const sc = new StringCodec();
// Establish a connection to the NATS demo server. This uses the
// native WebSocket support built into the NATS server.
const nc = await connect({
servers: ["wss://wallet.localtest.me/api/v0/broker"],
});
// Subscribe to the "echo" subject and define a message
// handler that will respond to the requester.
const sub = nc.subscribe("echo");
const handle = (msg) => {
console.log(`Received a request: ${sc.decode(msg.data)}`);
msg.respond(msg.data);
}
// Wait to receive messages from the subscription and handle them
// asynchronously..
(async () => {
for await (const msg of sub) handle(msg)
})();
// Now we can send a couple requests to that subject. Note how we
// are encoding the string data on request and decoding the reply
// message data.
let rep = await nc.request("echo", sc.encode("Hello!"));
console.log(`Received a reply: ${sc.decode(rep.data)}`);
rep = await nc.request("echo", sc.encode("World!"));
console.log(`Received a reply: ${sc.decode(rep.data)}`);
// Finally drain the connection which will handle any outstanding
// messages before closing the connection.
nc.drain();
</script>
</head>
</html>