104 lines
2.9 KiB
HTML
104 lines
2.9 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="en">
|
|
|
|
<head>
|
|
<meta charset="UTF-8" />
|
|
<title>Chat Room</title>
|
|
<script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
|
|
<style>
|
|
body {
|
|
font-family: Arial;
|
|
padding: 20px;
|
|
}
|
|
|
|
#chat-box {
|
|
border: 1px solid #ccc;
|
|
padding: 10px;
|
|
height: 300px;
|
|
overflow-y: scroll;
|
|
margin-bottom: 10px;
|
|
}
|
|
|
|
.message {
|
|
margin: 5px 0;
|
|
}
|
|
|
|
.message.you {
|
|
text-align: right;
|
|
color: blue;
|
|
}
|
|
|
|
.message.other {
|
|
text-align: left;
|
|
color: green;
|
|
}
|
|
</style>
|
|
</head>
|
|
|
|
<body>
|
|
|
|
<h2>Chat Room</h2>
|
|
<div>
|
|
<label>User ID: <input type="text" id="userId" value="1" /></label>
|
|
<label>Receiver ID: <input type="text" id="receiverId" value="2" /></label>
|
|
<label>Chat ID: <input type="text" id="chatId" value="chat123" /></label>
|
|
<button onclick="joinRoom()">Join Chat Room</button>
|
|
</div>
|
|
|
|
<div id="chat-box"></div>
|
|
|
|
<input type="text" id="message" placeholder="Type a message" />
|
|
<button onclick="sendMessage()">Send</button>
|
|
|
|
<script>
|
|
const socket = io("http://localhost:8000");
|
|
|
|
let chatId = '';
|
|
let userId = '';
|
|
let receiverId = '';
|
|
|
|
socket.on("connect", () => {
|
|
console.log("Connected to socket:", socket.id);
|
|
});
|
|
|
|
socket.on("chat-message", (data) => {
|
|
const chatBox = document.getElementById("chat-box");
|
|
const msg = document.createElement("div");
|
|
msg.className = "message " + (data.sender_xid == userId ? "you" : "other");
|
|
msg.innerText = `User ${data.sender_xid}: ${data.message}`;
|
|
chatBox.appendChild(msg);
|
|
chatBox.scrollTop = chatBox.scrollHeight;
|
|
});
|
|
|
|
function joinRoom() {
|
|
userId = document.getElementById("userId").value;
|
|
receiverId = document.getElementById("receiverId").value;
|
|
chatId = document.getElementById("chatId").value;
|
|
|
|
socket.emit("join-room", { chatId });
|
|
}
|
|
|
|
async function sendMessage() {
|
|
const messageText = document.getElementById("message").value;
|
|
if (!messageText) return;
|
|
|
|
const response = await fetch("http://localhost:8000/api/chat/user/send-message", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({
|
|
userId,
|
|
chatId,
|
|
message: messageText,
|
|
receiverId
|
|
})
|
|
});
|
|
|
|
const data = await response.json();
|
|
console.log("Message sent:", data);
|
|
|
|
document.getElementById("message").value = "";
|
|
}
|
|
</script>
|
|
</body>
|
|
|
|
</html> |