2025-12-26 13:37:00 +01:00

109 lines
3.4 KiB
HTML

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>WebSocket Test UI</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 16px;
background: #000;
color: #fff;
}
#messages {
border: 1px solid #222;
background: #111;
color: #fff;
height: 300px;
overflow: auto;
padding: 8px;
}
#status {
margin-bottom: 8px;
color: #23a559;
}
input,
button {
background: #23272a;
color: #fff;
border: 1px solid #444;
}
button {
background: #5865f2;
color: #fff;
border: none;
padding: 6px 16px;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background: #4752c4;
}
</style>
</head>
<body>
<h1>WebSocket Chat</h1>
<div id="status">Not connected</div>
<div id="messages"></div>
<input id="msg" placeholder="Type message..." style="width: 70%" />
<button id="send">Send</button>
<script>
const statusEl = document.getElementById("status");
const messagesEl = document.getElementById("messages");
const msgInput = document.getElementById("msg");
const sendBtn = document.getElementById("send");
// connect to same host and port the page was served from
const url =
(location.protocol === "https:" ? "wss://" : "ws://") +
location.host;
const ws = new WebSocket(url);
function addLine(text) {
const div = document.createElement("div");
div.textContent = text;
messagesEl.appendChild(div);
messagesEl.scrollTop = messagesEl.scrollHeight;
}
ws.addEventListener("open", () => {
statusEl.textContent = "Connected to " + url;
addLine("[system] connected");
});
ws.addEventListener("message", (e) => {
try {
const data = JSON.parse(e.data);
if (data.type === "welcome") {
addLine("[system] assigned id: " + data.id);
} else if (data.type === "message") {
addLine(`[${data.from}] ${data.text}`);
} else {
addLine("[unknown] " + e.data);
}
} catch (err) {
addLine("[raw] " + e.data);
}
});
ws.addEventListener("close", () =>
addLine("[system] disconnected"),
);
ws.addEventListener("error", () => addLine("[system] error"));
sendBtn.onclick = () => {
const text = msgInput.value.trim();
if (!text) return;
ws.send(text);
msgInput.value = "";
};
// allow Enter to send
msgInput.addEventListener("keydown", (e) => {
if (e.key === "Enter") sendBtn.click();
});
</script>
</body>
</html>