-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
61 lines (50 loc) · 1.37 KB
/
index.html
File metadata and controls
61 lines (50 loc) · 1.37 KB
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
<h1>Chat in Real Time</h1>
<!-- Messages -->
<pre id="messages" style="height: 400px; overflow: scroll"></pre>
<!-- Text box -->
<input
type="text"
id="messageBox"
placeholder="Type your message here"
style="display: block; width: 100%; margin-bottom: 10px; padding: 10px"
/>
<!-- Button -->
<button id="send" title="Send Message!" style="width: 100%; height: 30px">
Send Message
</button>
<script>
(function () {
const sendBtn = document.querySelector("#send");
const messages = document.querySelector("#messages");
const messageBox = document.querySelector("#messageBox");
let ws;
function showMessage(message) {
messages.textContent += `\n\n${message}`;
messages.scrollTop = messages.scrollHeight;
messageBox.value = "";
}
function init() {
if (ws) {
ws.onerror = ws.onopen = ws.onclose = null;
ws.close();
}
ws = new WebSocket("ws://localhost:7171");
ws.onopen = () => {
console.log("Connection opened.");
};
ws.onmessage = ({ data }) => showMessage(data);
ws.onclose = function () {
ws = null;
};
}
sendBtn.onclick = function () {
if (!ws) {
showMessage("Could not find a WebSocket connection.");
return;
}
ws.send(messageBox.value);
showMessage(messageBox.value);
};
init();
})();
</script>