summary refs log tree commit diff
path: root/crates/messenger_server/chat.html
blob: 0347cc175e6b698bc07c78fd697141f1eba1538b (plain) (blame)
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
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>WebSocket Chat</title>
    </head>
    <body>
        <h1>WebSocket Chat Example</h1>

        <input id="username" style="display:block; width:100px; box-sizing: border-box" type="text" placeholder="username">
        <button id="join-chat" type="button">Join Chat</button>
        <textarea id="chat" style="display:block; width:600px; height:400px; box-sizing: border-box" cols="30" rows="10"></textarea>
        <input id="input" style="display:block; width:600px; box-sizing: border-box" type="text" placeholder="chat">

        <script>
            const username = document.querySelector("#username");
            const join_btn = document.querySelector("#join-chat");
            const textarea = document.querySelector("#chat");
            const input = document.querySelector("#input");

            join_btn.addEventListener("click", function(e) {
                this.disabled = true;

                const websocket = new WebSocket("ws://localhost:3000/websocket");

                websocket.onopen = function() {
                    console.log("connection opened");
                    const data = { setUsername: username.value };
                    websocket.send(JSON.stringify(data));
                }

                const btn = this;

                websocket.onclose = function() {
                    console.log("connection closed");
                    btn.disabled = false;
                }

                websocket.onmessage = function(e) {
                    console.log("received message: "+e.data);
					console.log(JSON.parse(e.data));

					const data = extractData(e.data);
                    textarea.value += data+"\r\n";
                }

                input.onkeydown = function(e) {
                    if (e.key == "Enter") {
                        const data = {
                            userMessage: input.value,
                        }
                        websocket.send(JSON.stringify(data));
                        input.value = "";
                    }
                }
            });

			function extractData(data) {
				const d = JSON.parse(data);

				return data;
			}
        </script>
    </body>
</html>