48 lines
1.3 KiB
JavaScript
48 lines
1.3 KiB
JavaScript
// const id = 0;
|
|
if (id === undefined) {
|
|
throw "id is undefined!";
|
|
}
|
|
const ws = new WebSocket("ws://192.254.0.2:" + (9000 + id));
|
|
|
|
ws.onmessage = (event) => {
|
|
console.log(event.data);
|
|
if (typeof event.data == "string") {
|
|
let msg = JSON.parse(event.data);
|
|
if (event.data[0] == "[") {
|
|
// Handle list of users
|
|
users = msg;
|
|
let usersElems = [];
|
|
for (u of users) {
|
|
if (typeof u == "string") {
|
|
let un = document.createElement("div");
|
|
un.innerText = u;
|
|
usersElems.push(un);
|
|
}
|
|
}
|
|
document.getElementById("users").replaceChildren(...usersElems);
|
|
} else {
|
|
// Handle message
|
|
let msgs = document.getElementById("msgs");
|
|
let elem = document.createElement("p");
|
|
elem["data-id"] = msg.id;
|
|
elem.innerHTML =
|
|
"<span>" + users[msg.author] + " :</span> " + msg.content;
|
|
for (c of msgs.children) {
|
|
if (c["data-id"] > msg.id) {
|
|
msgs.insertBefore(elem, c);
|
|
return;
|
|
}
|
|
}
|
|
msgs.appendChild(elem);
|
|
}
|
|
}
|
|
};
|
|
|
|
document.getElementById("send").onsubmit = (event) => {
|
|
event.preventDefault();
|
|
// console.log(event, document.getElementById("sendcontent").value);
|
|
let content = document.getElementById("sendcontent");
|
|
ws.send("send " + content.value);
|
|
content.value = "";
|
|
};
|