Spaces:
Sleeping
Sleeping
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>CustomBoxServer</title> | |
| <style> | |
| body { font-family: Arial, sans-serif; } | |
| #messages { list-style-type: none; padding: 0; } | |
| #messages li { margin: 5px 0; } | |
| #chat { display: flex; } | |
| #chat input { flex: 1; } | |
| #chat button { margin-left: 5px; } | |
| </style> | |
| </head> | |
| <body> | |
| <h1>Chat Application</h1> | |
| <ul id="messages"></ul> | |
| <div id="chat"> | |
| <input id="username" type="text" placeholder="Your name" /> | |
| <input id="color" type="text" placeholder="Your color (e.g., red)" /> | |
| <input id="message" type="text" placeholder="Type a message..." /> | |
| <button id="send">Send</button> | |
| </div> | |
| <script src="/socket.io/socket.io.js"></script> | |
| <script> | |
| const socket = io("http://localhost:8086", { | |
| path: '/socket.io/', | |
| transports: ['websocket', 'polling'], // Ensure compatibility with older clients | |
| }); | |
| let username; | |
| document.getElementById('send').onclick = function() { | |
| if (!username) { | |
| username = document.getElementById('username').value; | |
| const color = document.getElementById('color').value; | |
| if (username && color) { | |
| socket.emit("user joined", username, color); // Emit user joined event | |
| } | |
| } | |
| const messageInput = document.getElementById('message'); | |
| if (messageInput.value) { | |
| // Send message using socket.send() | |
| socket.send({ msg: messageInput.value }); | |
| messageInput.value = ''; // Clear input field after sending | |
| } | |
| }; | |
| // Listen for messages from server using socket.on() | |
| socket.on("message", function(data) { | |
| const item = document.createElement("li"); | |
| item.style.color = data.color || "black"; | |
| item.textContent = `${data.nick}: ${data.msg}`; | |
| document.getElementById("messages").appendChild(item); | |
| }); | |
| // Listen for user join notifications | |
| socket.on("user joined", function(data) { | |
| const item = document.createElement("li"); | |
| item.style.color = data.color || "black"; | |
| item.textContent = `${data.username} has joined the chat`; | |
| document.getElementById("messages").appendChild(item); | |
| }); | |
| // Listen for user left notifications | |
| socket.on("user left", function(data) { | |
| const item = document.createElement("li"); | |
| item.textContent = `${data.username} has left the chat`; | |
| document.getElementById("messages").appendChild(item); | |
| }); | |
| </script> | |
| </body> | |
| </html> | |