-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.ts
55 lines (45 loc) · 1.67 KB
/
client.ts
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 "./styles.css";
import PartySocket from "partysocket";
declare const PARTYKIT_HOST: string;
let pingInterval: ReturnType<typeof setInterval>;
// Let's append all the messages we get into this DOM element
const output = document.getElementById("app") as HTMLDivElement;
const sendBtn = document.getElementById("sendBtn") as HTMLButtonElement;
const clearBtn = document.getElementById("clear") as HTMLButtonElement;
// Helper function to add a new line to the DOM
function add(text: string) {
output.appendChild(document.createTextNode(text));
output.appendChild(document.createElement("br"));
}
// A PartySocket is like a WebSocket, except it's a bit more magical.
// It handles reconnection logic, buffering messages while it's offline, and more.
const conn = new PartySocket({
host: PARTYKIT_HOST,
room: "my-new-room",
});
// You can even start sending messages before the connection is open!
conn.addEventListener("message", (event) => {
console.log(`Received -> ${event.data}`);
add(`Received -> ${event.data}`);
});
sendBtn.addEventListener("click", () => {
console.log("sending message");
let message = document.getElementById("message") as HTMLInputElement;
console.log(message.value);
conn.send(message.value);
message.value = "";
});
clearBtn.addEventListener("click", () => {
output.innerHTML = "";
});
// Let's listen for when the connection opens
// And send a ping every 2 seconds right after
conn.addEventListener("open", () => {
add("Connected!");
add("Sending a ping every 2 seconds...");
// TODO: make this more interesting / nice
// clearInterval(pingInterval);
// pingInterval = setInterval(() => {
// conn.send("ping");
// }, 1000);
});