mirror of
https://github.com/DarrylNixon/drawbridge
synced 2024-04-22 12:17:07 -07:00
Add example chat app
This commit is contained in:
parent
2de8736d24
commit
e6e1c51e83
3 changed files with 182 additions and 0 deletions
65
examples/chat.html
Normal file
65
examples/chat.html
Normal file
|
@ -0,0 +1,65 @@
|
|||
<!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>
|
Loading…
Add table
Add a link
Reference in a new issue