67 lines
No EOL
2.7 KiB
HTML
67 lines
No EOL
2.7 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>Web Chat Client</title>
|
|
<script src="https://cdn.socket.io/4.5.0/socket.io.min.js"></script>
|
|
<style>
|
|
body { font-family: Arial, sans-serif; margin: 0; padding: 0; display: flex; flex-direction: column; height: 100vh; }
|
|
#chat { flex: 1; overflow-y: auto; padding: 10px; border-bottom: 1px solid #ccc; }
|
|
#messageInput { display: flex; padding: 10px; }
|
|
#messageInput input { flex: 1; padding: 10px; font-size: 16px; }
|
|
#messageInput button { padding: 10px; font-size: 16px; }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div id="chat"></div>
|
|
<div id="messageInput">
|
|
<input type="text" id="message" placeholder="Type a message...">
|
|
<button onclick="sendMessage()">Send</button>
|
|
</div>
|
|
|
|
<script>
|
|
// Ask the user for the server address
|
|
const serverUrl = prompt("Enter the WebSocket server URL (e.g., http://localhost:5000):") || 'http://localhost:5000';
|
|
const socket = io(serverUrl); // Connect to the WebSocket server
|
|
|
|
const chatDiv = document.getElementById('chat');
|
|
const messageInput = document.getElementById('message');
|
|
|
|
// Ask the user for their username and chat room
|
|
let username = prompt("Enter your username:");
|
|
let chatRoom = prompt("Enter chat room (default: 'default')") || 'default';
|
|
|
|
// Join the chat room
|
|
console.log('Joining chat room:', { username: username, chat_room: chatRoom });
|
|
socket.emit('join', { username: username, chat_room: chatRoom });
|
|
|
|
// Log connection status
|
|
socket.on('connect', () => {
|
|
console.log('Connected to WebSocket server');
|
|
});
|
|
|
|
socket.on('disconnect', () => {
|
|
console.log('Disconnected from WebSocket server');
|
|
});
|
|
|
|
// Listen for messages from the server
|
|
socket.on('message', (data) => {
|
|
const messageElement = document.createElement('div');
|
|
messageElement.textContent = `${data.username || 'Server'}: ${data.message}`;
|
|
chatDiv.appendChild(messageElement);
|
|
chatDiv.scrollTop = chatDiv.scrollHeight; // Auto-scroll to the bottom
|
|
});
|
|
|
|
// Send a message to the server
|
|
function sendMessage() {
|
|
const message = messageInput.value;
|
|
if (message.trim() !== '') {
|
|
console.log('Sending message:', { username: username, chat_room: chatRoom, message: message });
|
|
socket.emit('send_message', { username: username, chat_room: chatRoom, message: message });
|
|
messageInput.value = ''; // Clear the input field
|
|
}
|
|
}
|
|
</script>
|
|
</body>
|
|
</html> |