-
Notifications
You must be signed in to change notification settings - Fork 0
/
p2p.js
38 lines (30 loc) · 1.02 KB
/
p2p.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
class Identity {
constructor(friendlyName) {
this.clientId = crypto.getRandomValues(new Uint32Array(1))[0];
this.friendlyName = friendlyName;
}
}
class PubSubClient {
constructor(onMessageReceivedCallback) {
this.connected = false;
this.onMessageReceivedCallback = onMessageReceivedCallback;
}
async connect(identity, uniqueId) {
if(this.connected) return;
this.metadata = { uniqueId: uniqueId, ...identity };
const ably = new Ably.Realtime.Promise({ authUrl: '/api/createTokenRequest' });
this.channel = await ably.channels.get(`p2p-sample-${uniqueId}`);
this.channel.subscribe((message) => {
this.onMessageReceivedCallback(message.data, this.metadata);
});
this.connected = true;
}
sendMessage(message, targetClientId) {
if (!this.connected) {
throw "Client is not connected";
}
message.metadata = this.metadata;
message.forClientId = targetClientId ? targetClientId : null;
this.channel.publish({ name: "myMessageName", data: message});
}
}