|
| 1 | +<!DOCTYPE html> |
| 2 | +<html lang="en"> |
| 3 | +<head> |
| 4 | + <meta charset="UTF-8"> |
| 5 | + <title>Socket.IO Test</title> |
| 6 | + <script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script> |
| 7 | +</head> |
| 8 | +<body> |
| 9 | + <h2>Socket.IO Chat Test</h2> |
| 10 | + <input id="roomInput" placeholder="Room ID" /> |
| 11 | + <button onclick="joinRoom()">Join Room</button> |
| 12 | + <br><br> |
| 13 | + <input id="messageInput" placeholder="Message" /> |
| 14 | + <button onclick="sendMessage()">Send Message</button> |
| 15 | + <div id="messages"></div> |
| 16 | + |
| 17 | + <script> |
| 18 | + const socket = io("http://localhost:3002"); |
| 19 | + |
| 20 | + socket.on("connect", () => { |
| 21 | + console.log("Connected to Socket.IO server"); |
| 22 | + }); |
| 23 | + |
| 24 | + socket.on("chatMessage", (message) => { |
| 25 | + const messagesDiv = document.getElementById("messages"); |
| 26 | + const messageElem = document.createElement("p"); |
| 27 | + messageElem.textContent = `Received: ${message.text}`; |
| 28 | + messagesDiv.appendChild(messageElem); |
| 29 | + }); |
| 30 | + |
| 31 | + function joinRoom() { |
| 32 | + const roomId = document.getElementById("roomInput").value; |
| 33 | + socket.emit("joinRoom", roomId); |
| 34 | + console.log(`Joined room: ${roomId}`); |
| 35 | + } |
| 36 | + |
| 37 | + function sendMessage() { |
| 38 | + const roomId = document.getElementById("roomInput").value; |
| 39 | + const text = document.getElementById("messageInput").value; |
| 40 | + const message = { roomId, userId: "user1", text }; |
| 41 | + socket.emit("sendMessage", message); |
| 42 | + console.log(`Sent message: ${text}`); |
| 43 | + } |
| 44 | + </script> |
| 45 | +</body> |
| 46 | +</html> |
| 47 | + |
0 commit comments