Files
fastapi_best_architecture/backend/static/ws.html
2025-01-23 13:12:46 +08:00

93 lines
3.0 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Socket.IO Task Notifications</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
}
#notifications {
margin-top: 20px;
padding: 10px;
border: 1px solid #ccc;
max-height: 300px;
overflow-y: auto;
}
.notification {
padding: 10px;
margin-bottom: 10px;
background-color: #f9f9f9;
border: 1px solid #ddd;
border-radius: 4px;
}
.notification.new {
background-color: #d3f9d8;
}
</style>
</head>
<body>
<h1>Task Notifications</h1>
<p>Waiting for task notifications...</p>
<div id="notifications"></div>
<!-- Load Socket.IO client -->
<script src="https://cdn.socket.io/4.5.1/socket.io.min.js"></script>
<script>
// Establish a connection to the server
const socket = io('http://127.0.0.1:8000', {
autoConnect: true,
path: '/ws/socket.io',
reconnection: true,
reconnectionAttempts: 3,
reconnectionDelay: 1000,
transports: ['websocket'],
auth: {
session_uuid: 'da985430-43b3-4860-a20a-97cc8e8e0b76',
token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzZXNzaW9uX3V1aWQiOiJkYTk4NTQzMC00M2IzLTQ4NjAtYTIwYS05N2NjOGU4ZTBiNzYiLCJleHAiOjE3Mzc2MzQwODUsInN1YiI6IjEifQ.QeXNtXhHG4cm5GRzOtv2wqZXi6HdqACmW_UjC4JLPsk'
}
});
// Handle 'task_notification' event
socket.on('task_notification', (data) => {
// Get the notifications container
const notificationsContainer = document.getElementById('notifications');
// Create a new div for the notification
const notificationDiv = document.createElement('div');
notificationDiv.classList.add('notification', 'new');
notificationDiv.innerHTML = `
<strong>Task Notification:</strong>
<p>${data.msg}</p>
<small>Received at: ${new Date().toLocaleTimeString()}</small>
`;
// Append the new notification to the container
notificationsContainer.appendChild(notificationDiv);
// Scroll to the bottom to show the latest notification
notificationsContainer.scrollTop = notificationsContainer.scrollHeight;
});
// Handle connection errors
socket.on('connect_error', (error) => {
console.error('Connection error:', error);
alert('Unable to connect to the server. Please check your connection.');
});
socket.on('connect', () => {
console.log('Connected to server');
});
socket.on('disconnect', () => {
console.log('Disconnected from server');
});
</script>
</body>
</html>