blob: bea1582d1117b37998e8968f91ad7e2e1cdeb59f (
plain)
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
|
import { log } from "./logger";
import { CSPacket, SCPacket } from "./types";
import { User } from "./user";
export class Room {
el: HTMLElement
name: string
users: Map<string, User> = new Map()
websocket: WebSocket
constructor(name: string) {
this.name = name
this.el = document.createElement("div")
this.websocket = new WebSocket(`ws://${window.location.host}/room/${encodeURIComponent(name)}`)
this.websocket.onclose = () => this.websocket_close()
this.websocket.onopen = () => this.websocket_open()
this.websocket.onmessage = (ev) => {
this.websocket_message(JSON.parse(ev.data))
}
}
websocket_send(data: CSPacket) {
log("ws", `-> ${data.receiver ?? "*"}`, data)
this.websocket.send(JSON.stringify(data))
}
websocket_message(packet: SCPacket) {
if (packet.join) {
log("*", `${this.name} ${packet.sender} joined`);
this.users.set(packet.sender, new User(this, packet.sender, !packet.stable))
return
}
const sender = this.users.get(packet.sender)
if (!sender) return console.warn(`unknown sender ${packet.sender}`)
if (packet.leave) {
log("*", `${this.name} ${packet.sender} left`);
sender.leave()
this.users.delete(packet.sender)
return
}
if (!packet.data) return console.warn("dataless packet")
log("ws", `<- ${packet.sender}: `, packet.data);
if (packet.data.ice_candiate) sender.add_ice_candidate(packet.data.ice_candiate)
if (packet.data.offer) sender.on_offer(packet.data.offer)
if (packet.data.answer) sender.on_answer(packet.data.answer)
}
websocket_close() {
log("ws", "websocket closed");
}
websocket_open() {
log("ws", "websocket opened");
this.websocket.send(Math.random().toString())
}
}
|