Add a little chat demo

This commit is contained in:
Dane Johnson 2022-10-13 12:51:46 -05:00
parent 6189b82bd3
commit 92f7e5aa5f

68
public/index.html Normal file
View File

@ -0,0 +1,68 @@
<!DOCTYPE html>
<html>
<body>
<script
src="https://code.jquery.com/jquery-3.6.1.slim.min.js"
integrity="sha256-w8CvhFs7iHNVUtnSP0YKEg00p9Ih13rlL9zGqvLdePA="
crossorigin="anonymous"
></script>
<h1 id="roomName">
Not Connected
</h1>
<div>
<button id="hostBtn" disabled>Host</button>
<input id="roomTxt" type="text">
<button id="joinBtn" disabled>Join</button>
</div>
<textarea readonly></textarea>
<div>
<input id="chatTxt" type="text" disabled>
<button id="chatBtn" disabled>Chat</button>
</div>
<script>
const ws = new WebSocket("ws://localhost:8080");
ws.addEventListener('open', e => {
$("#hostBtn").attr('disabled', false);
$("#joinBtn").attr('disabled', false);
});
$("#hostBtn").on('click', e => ws.send("HOST:"));
$("#joinBtn").on('click', e => {
const roomCode = $('#roomTxt').val();
const msg = `JOIN: ${roomCode}`;
ws.send(msg);
$("#roomName").text(roomCode);
});
$("#chatBtn").on('click', e => {
let text = $('#chatTxt').val();
$('#chatTxt').val('');
msg = `CHAT: ${text}`;
ws.send(msg);
});
ws.addEventListener('message', e => {
const msg = e.data;
const pos = msg.indexOf(':');
const command = msg.substring(0, pos);
const args = msg.substring(pos+1).split(',');
switch(command) {
case "ROOM_CODE":
$("#roomName").text(args[0]);
// Fallthrough
case "JOIN_OK":
$("#chatTxt").attr('disabled', false);
$("#chatBtn").attr('disabled', false);
break;
case "CHAT":
let text = $("textarea").val();
text = text += `\n${args[0]}`;
$("textarea").val(text);
default:
console.log("Unhandled message", msg);
}
});
</script>
</body>
</html>