-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
54 lines (45 loc) · 1.77 KB
/
index.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
var app = new Vue({
el: '#app',
data: {
p2pClient: null,
p2pServer: null,
friendlyName: "Player-" + crypto.getRandomValues(new Uint32Array(1))[0],
uniqueId: "Session"
},
computed: {
state: function() { return this.p2pClient?.state; },
transmittedServerState: function() { return this.p2pClient?.serverState; },
joinedOrHosting: function () { return this.p2pClient != null || this.p2pServer != null; },
},
methods: {
host: async function(evt) {
evt.preventDefault();
const pubSubClient = new PubSubClient((message, metadata) => {
handleMessagefromAbly(message, metadata, this.p2pClient, this.p2pServer);
});
const identity = new Identity(this.friendlyName);
this.p2pServer = new P2PServer(identity, this.uniqueId, pubSubClient);
this.p2pClient = new P2PClient(identity, this.uniqueId, pubSubClient);
await this.p2pServer.connect();
await this.p2pClient.connect();
},
join: async function(evt) {
evt.preventDefault();
const pubSubClient = new PubSubClient((message, metadata) => {
handleMessagefromAbly(message, metadata, this.p2pClient, this.p2pServer);
});
const identity = new Identity(this.friendlyName);
this.p2pClient = new P2PClient(identity, this.uniqueId, pubSubClient);
await this.p2pClient.connect();
}
}
});
function shouldHandleMessage(message, metadata) {
return message.forClientId == null || !message.forClientId || (message.forClientId && message.forClientId === metadata.clientId);
}
function handleMessagefromAbly(message, metadata, p2pClient, p2pServer) {
if (shouldHandleMessage(message, metadata)) {
p2pServer?.onReceiveMessage(message);
p2pClient?.onReceiveMessage(message);
}
}