infa735-drawbridge/examples/chat.html

65 lines
1.7 KiB
HTML
Raw Normal View History

2023-12-04 14:09:05 -08:00
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Chat</title>
<style>
#chat {
height: 400px;
border: 1px solid #aaaaaa;
overflow: auto;
}
#message {
width: 350px;
}
</style>
</head>
<body>
<div id="chat"></div>
<input id="message" type="text">
<button id="send">Send</button>
<script>
var ws = new WebSocket("ws://10.211.55.3/"),
chat = document.getElementById("chat"),
messageInput = document.getElementById("message"),
sendButton = document.getElementById("send");
ws.onopen = function (event) {
console.log("WebSocket is open now.");
};
ws.onclose = function (event) {
console.log("WebSocket is closed now.");
};
ws.onerror = function (event) {
console.error("WebSocket error observed:", event);
};
ws.onmessage = function (event) {
var payload = JSON.parse(event.data),
p = document.createElement("p");
p.style.wordWrap = "break-word";
p.innerHTML = "<strong>" + payload.sender + "</strong>: " + payload.message;
chat.appendChild(p);
// Automatically scroll to bottom
chat.scrollTop = chat.scrollHeight;
};
sendButton.onclick = function () {
var message = messageInput.value;
if (ws.readyState === WebSocket.OPEN) {
ws.send(message);
messageInput.value = "";
} else {
console.error("WebSocket is not open. Ready state:", ws.readyState);
}
};
</script>
</body>
</html>