Source Code:
(back to article)
Submit
Result:
Report an issue
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>WebSocket Echo Chat</title> </head> <body> <textarea id="chatBox" readonly style="width: 100%; height: 300px"> </textarea> <br /> <input type="text" id="messageInput" placeholder="Type a message..." style="width: 75%" /> <button onclick="sendMessage()">Send</button> <button onclick="closeConnection()">Close Connection</button> </body> <script> const chatBox = document.getElementById("chatBox"); const messageInput = document.getElementById("messageInput"); const socket = new WebSocket("wss://echo.websocket.org"); socket.addEventListener("open", function (event) { chatBox.value += "Connected to the echo server\n"; }); socket.addEventListener("message", function (event) { chatBox.value += "Echoed back: " + event.data + "\n"; }); function sendMessage() { const message = messageInput.value; if (!message) return; socket.send(message); chatBox.value += "You: " + message + "\n"; messageInput.value = ""; } function closeConnection() { if (socket.readyState === WebSocket.OPEN) { socket.close(1000, "The user closed the connection"); chatBox.value += "Connection closed by user\n"; } else { alert("Connection not open or already closed."); } } window.addEventListener("beforeunload", function () { if (socket.readyState === WebSocket.OPEN) { socket.close(1000, "The page is unloading"); } }); </script> </html>