<!DOCTYPE html> <html> <head> <meta charset=“UTF-8”/> <title>Multiplayer Chat…
- User
- Assistant
{ margin-bottom: 10px; }
// When the WebSocket connection is established socket.onopen = function() { console.log("Connected to server"); };
// When a message is received from the server socket.onmessage = function(event) { var data = JSON.parse(event.data); var li = document.createElement("li"); li.appendChild(document.createTextNode(data.name + ": " + data.message)); document.getElementById("messages").appendChild(li); };
// When the WebSocket connection is closed socket.onclose = function(event) { console.log("Disconnected from server"); };
// When the user clicks the send button document.getElementById("send").onclick = function() { var name = document.getElementById("name").value; var message = document.getElementById("message").value;
// Send a message to the server socket.send(JSON.stringify({ name: name, message: message })); // Clear the input fields document.getElementById("name").value = ""; document.getElementById("message").value = "";};