Files

26 lines
755 B
HTML

<!doctype html>
<meta charset="utf-8" />
<title>WebSocket test</title>
<button id="send">Send</button>
<pre id="log"></pre>
<script>
const logEl = document.getElementById("log");
const log = (msg) => (logEl.textContent += msg + "\n");
const wsProto = location.protocol === "https:" ? "wss:" : "ws:";
const ws = new WebSocket(`${wsProto}//${location.host}/ws`);
ws.onopen = () => {
log("open");
ws.send(JSON.stringify({ type: "ECHO", text: "hello" }));
};
ws.onmessage = (event) => log("recv: " + event.data);
ws.onclose = (event) => log(`close ${event.code}`);
ws.onerror = () => log("error");
document.getElementById("send").onclick = () => {
ws.send(JSON.stringify({ type: "ECHO", text: "button " }));
};
</script>