-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
51 lines (41 loc) · 1.65 KB
/
index.html
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
<html>
<head>
<title>WebSocket Chat</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
</head>
<body>
<div class="h-screen w-screen flex flex-col justify-between">
<div id="chat" class="p-3 overflow-auto">
</div>
<div class="flex">
<input id="message" type="text" class="px-3 w-full border-t border-gray-300 outline-none text-gray-700" placeholder="Type your message..." />
<button class="px-8 py-3 bg-green-500 text-white hover:bg-green-600 transition-colors" onclick="sendMessage()">Send</button>
</div>
</div>
<script>
const ws = new WebSocket("ws://localhost:3000");
ws.addEventListener("message", function(event) {
const data = JSON.parse(event.data);
if (data.type === "message") {
addMessage(data.data);
}
});
function sendMessage() {
const message = document.getElementById("message").value;
if (!message) return false;
ws.send(JSON.stringify({ type: "message", data: message }));
addMessage(message);
document.getElementById("message").value = "";
}
function addMessage(message) {
const node = document.createElement("P");
const text = document.createTextNode(message);
node.appendChild(text);
node.classList.add("text-gray-700", "py-1");
document.getElementById("chat").appendChild(node);
}
</script>
</body>
</html>