savinmax e4523df602
Some checks failed
CI / test (push) Successful in 1m10s
CI / lint (push) Successful in 30s
Release / release (push) Failing after 31s
Init
2025-08-02 18:33:50 +02:00

86 lines
2.4 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Websocket relay example</title>
</head>
<body>
<style>
.chat {
width: 600px;
height: 500px;
border: 1px solid black;
overflow-y: scroll;
background-color: beige;
padding: 15px;
box-sizing: content-box;
}
.chat .bubble {
width: calc(100% - 30px);
border-radius: 10px;
background-color: bisque;
font-size: 12px;
margin-bottom: 10px;
padding: 5px 10px;
}
.chat .error {
color: red;
margin: 10px 0;
}
</style>
<div>
<h1>P2P Chat</h1>
<div class="chat" id="box"></div>
<textarea id="message"></textarea>
<br />
<button id="send" disabled>Send</button>
</div>
<script>
const chat = document.getElementById("box");
const message = document.getElementById("message");
const btn = document.getElementById("send");
const name = Date.now().toString(36);
let retry = 1000;
let ws;
function connect() {
ws = new WebSocket('ws://localhost:8000/');
ws.onmessage = (event) => {
console.log('Received:', event.data);
chat.innerHTML += `<div class="bubble">${event.data}</div>`;
};
ws.onopen = () => {
btn.removeAttribute("disabled");
ws.send(`${name} joined the chat`);
};
ws.onerror = (ev) => {
btn.setAttribute("disabled", "disabled");
chat.innerHTML += `<div class="error">Failed to connect to websocket, retrying...</div>`;
console.error(ev);
delete ws.onmessage;
delete ws.onopen;
setTimeout(connect, retry);
retry *= 2;
};
}
btn.addEventListener("click", (ev) => {
ev.preventDefault();
const msg = message.value.trim();
if (!msg) {
return;
}
const data = `${name}<br>${msg}`;
ws.send(data);
message.value = "";
});
connect();
</script>
</body>
</html>