-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathbasicusage.js
85 lines (71 loc) · 2.36 KB
/
basicusage.js
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
/**
* @summary Basic usage of web-pubsub-client
*/
const { WebPubSubClient } = require("@azure/web-pubsub-client");
const { WebPubSubProtobufReliableProtocol } = require("@azure/web-pubsub-client-protobuf");
const { WebPubSubServiceClient } = require("@azure/web-pubsub");
require("dotenv").config();
const hubName = "sample_chat";
const groupName = "testGroup";
const serviceClient = new WebPubSubServiceClient(process.env.WPS_CONNECTION_STRING, hubName);
const fetchClientAccessUrl = async (_) => {
return (
await serviceClient.getClientAccessToken({
roles: [`webpubsub.joinLeaveGroup.${groupName}`, `webpubsub.sendToGroup.${groupName}`],
})
).url;
};
async function main() {
let client = new WebPubSubClient(
{
getClientAccessUrl: fetchClientAccessUrl,
},
{ protocol: WebPubSubProtobufReliableProtocol() }
);
client.on("connected", (e) => {
console.log(`Connection ${e.connectionId} is connected.`);
});
client.on("disconnected", (e) => {
console.log(`Connection disconnected: ${e.message}`);
});
client.on("server-message", (e) => {
if (e.message.data instanceof ArrayBuffer) {
console.log(`Received message ${Buffer.from(e.message.data).toString("base64")}`);
} else {
console.log(`Received message ${e.message.data}`);
}
});
client.on("group-message", (e) => {
if (e.message.data instanceof ArrayBuffer) {
console.log(
`Received message from ${e.message.group} ${Buffer.from(e.message.data).toString("base64")}`
);
} else {
console.log(`Received message from ${e.message.group} ${e.message.data}`);
}
});
await client.start();
await client.joinGroup(groupName);
await client.sendToGroup(groupName, "hello world", "text", {
fireAndForget: true,
});
await client.sendToGroup(groupName, { a: 12, b: "hello" }, "json");
await client.sendToGroup(groupName, "hello json", "json");
var buf = Buffer.from("aGVsbG9w", "base64");
await client.sendToGroup(
groupName,
buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength),
"binary"
);
await delay(1000);
await client.stop();
}
main().catch((e) => {
console.error("Sample encountered an error", e);
process.exit(1);
});
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}