-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathsimple.html
58 lines (50 loc) · 1.63 KB
/
simple.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
crossorigin="anonymous">
</head>
<body>
<!-- a place to record messages -->
<div id="messages" class="container"></div>
<!-- load a script -->
<script type="module">
import { connect, StringCodec } from '../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();
</script>
</body>
</html>