Skip to content

Instantly share code, notes, and snippets.

@wallyqs
Created October 15, 2020 17:54
Show Gist options
  • Save wallyqs/8c10dbe8981d55f04198fd2dc92ac98e to your computer and use it in GitHub Desktop.
Save wallyqs/8c10dbe8981d55f04198fd2dc92ac98e to your computer and use it in GitHub Desktop.
NATS.js websockets
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script type="module">
import { connect, StringCodec } from "/nats.mjs";
document.addEventListener("DOMContentLoaded", function() {
console.log("Connecting to NATS...");
let intv = null;
let nc = null;
const opts = {
servers: "wss://connect.ngs.synadia-test.com:443",
ws: false
};
connect(opts).then(function(c) {
nc = c;
console.log("connect ok!");
const sc = StringCodec();
intv = window.setInterval(function() {
console.log("publish triggered!");
nc.publish("foo", sc.encode("Hello, NATS WebSockets!"));
}, 3000);
const sub = nc.subscribe("bar");
(async () => {
for await (const m of sub) {
console.log(`RECV: ${sc.decode(m.data)}`);
}
})();
}).catch(function(err) {
console.log("connect failed");
console.log(err);
if (intv) {
window.clearInterval(intv);
}
if (nc) {
nc.close();
}
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment