Wyle.Gong-巩文昕 7a1aae1e2f ui
2025-04-23 11:21:08 +08:00

42 lines
1.2 KiB
JavaScript

import { connect, StringCodec } from '../esm/nats.js'
// add an entry to the document
function addEntry(s) {
const p = document.createElement("pre");
p.appendChild(document.createTextNode(s));
document.getElementById("messages").appendChild(p);
}
const sc = StringCodec();
const init = async function () {
// create a connection
const nc = await connect({ servers: 'ws://localhost:9222' })
addEntry('connected to NATS!');
// simple publisher
nc.publish('hello', sc.encode('nats'))
addEntry('published a message to `hello`');
// simple subscriber, if the message has a reply subject
// send a reply
const sub = await nc.subscribe('help');
(async () => {
addEntry('listening for request on `help`');
for await (const m of sub) {
m.respond(sc.encode(`I can help ${sc.decode(m.data)}`));
}
})().then()
// request data - requests only receive one message
// to receive multiple messages, create a subscription
addEntry('making a request to `help`');
const msg = await nc.request('help', sc.encode('nats request'))
addEntry(`got response '${sc.decode(msg.data)}'`);
// close the connection
nc.close();
addEntry('closed the connection');
}
init();