Created
August 3, 2025 19:22
-
-
Save gptshubham595/5a11e39d1ccc6d68ca16f8bb8efaf94d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8" /> | |
| <title>WebSocket Chat Client</title> | |
| <style> | |
| body { | |
| font-family: Arial, sans-serif; | |
| margin: 40px; | |
| } | |
| #messages { | |
| border: 1px solid #ccc; | |
| height: 300px; | |
| overflow-y: auto; | |
| padding: 10px; | |
| margin-bottom: 10px; | |
| background-color: #f9f9f9; | |
| } | |
| #messageInput { | |
| width: 70%; | |
| padding: 10px; | |
| font-size: 16px; | |
| } | |
| #sendButton { | |
| padding: 10px 20px; | |
| font-size: 16px; | |
| margin-left: 10px; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <h2>WebSocket Chat Client</h2> | |
| <div id="messages"></div> | |
| <input type="text" id="messageInput" placeholder="Type your message..." /> | |
| <button id="sendButton">Send</button> | |
| <script> | |
| const room = prompt("Enter room name", "lobby") || "lobby"; | |
| const socket = new WebSocket(`ws://localhost:8080?room=${room}`); | |
| const messagesDiv = document.getElementById("messages"); | |
| const input = document.getElementById("messageInput"); | |
| const sendBtn = document.getElementById("sendButton"); | |
| socket.addEventListener('open', () => { | |
| appendMessage("β Connected to WebSocket server in room: " + room); | |
| }); | |
| socket.addEventListener('message', async (event) => { | |
| const data = event.data; | |
| if (data instanceof Blob) { | |
| const text = await data.text(); // Convert Blob to string | |
| appendMessage("π€ " + text); | |
| } else { | |
| appendMessage("π€ " + data); | |
| } | |
| }); | |
| sendBtn.addEventListener('click', () => { | |
| const msg = input.value.trim(); | |
| if (msg) { | |
| socket.send(msg); | |
| appendMessage("π§βπ» You: " + msg); | |
| input.value = ''; | |
| } | |
| }); | |
| function appendMessage(msg) { | |
| const el = document.createElement("div"); | |
| el.textContent = msg; | |
| messagesDiv.appendChild(el); | |
| messagesDiv.scrollTop = messagesDiv.scrollHeight; | |
| } | |
| // Optional: send on Enter key | |
| input.addEventListener('keydown', (e) => { | |
| if (e.key === 'Enter') sendBtn.click(); | |
| }); | |
| </script> | |
| </body> | |
| </html> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment