-
Notifications
You must be signed in to change notification settings - Fork 2
/
peerJsWrapper.js
71 lines (59 loc) · 2.01 KB
/
peerJsWrapper.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
// import peerjs from "https://cdn.skypack.dev/peerjs"
const p2p = (() => {
const setupDeps = () => {
const peerJSScript = document.createElement("script")
peerJSScript.src = "https://unpkg.com/[email protected]/dist/peerjs.min.js"
const peerJSGroupsScript = document.createElement("script")
peerJSGroupsScript.src = "https://cdn.jsdelivr.net/gh/ElizabethHudnott/peerjs-groups@master/dist/peerjs-groups.js"
document.body.appendChild(peerJSScript)
document.body.appendChild(peerJSGroupsScript)
}
setupDeps()
return {}
})()
p2p.initializeFederation = (initOptions) => new Promise(resolve => {
const {
clientId=crypto.randomUUID(),
federationId,
signalingServerHost="0.peerjs.com",
signalingServerPort=443,
newUserCallback,
newMessageCallback
} = initOptions
p2p.group = new PeerGroup((err)=> {
console.error("Error initializing federation:", err)
}, {
host: signalingServerHost,
port: signalingServerPort,
debug: 2
})
p2p.group.addEventListener('connected', (e) => {
console.log(`Connected to federation ${e.sessionID}`);
p2p.clientId = clientId
p2p.federationId = e.sessionID
})
p2p.group.addEventListener('joined', (e) => {
console.log(`Joined federation ${e.sessionID}`);
p2p.clientId = clientId
p2p.federationId = e.sessionID
resolve({ clientId: p2p.clientId, federationId: p2p.federationId })
})
p2p.group.addEventListener('userpresent', (e) => {
console.log(`New User`, e.userID)
newUserCallback(e)
})
p2p.group.addEventListener('message', (e) => {
// console.log(`Message received:`, e.message)
newMessageCallback(e)
})
// p2p.group.addEventListener('joined', (e) => console.log(`Joined session ${e.sessionId}`))
console.log(`Attempting connection to federation ${federationId} from ${clientId}`)
p2p.group.connect(federationId, clientId)
})
p2p.sendDataToPeer = (peerId, data) => {
p2p.group.sendPrivate(peerId, data)
}
p2p.broadcastData = (data) => {
p2p.group.send(data)
}
export default p2p