1
0
mirror of https://gitlab.com/MoonTestUse1/AdministrationItDepartmens.git synced 2025-08-14 00:25:46 +02:00

add websockets support22

This commit is contained in:
MoonTestUse1
2025-01-05 01:41:26 +06:00
parent 99f3d6520e
commit 2000ed7c13
2 changed files with 38 additions and 8 deletions

View File

@@ -6,17 +6,29 @@ class WebSocketClient {
private maxReconnectAttempts = 5
private reconnectTimeout = 3000
private messageHandlers: ((data: any) => void)[] = []
private currentType: 'admin' | 'employee' | null = null
private currentId: number | undefined = undefined
// Состояние подключения
isConnected = ref(false)
connect(type: 'admin' | 'employee', id?: number) {
this.currentType = type
this.currentId = id
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
const baseUrl = `${protocol}//${window.location.host}`
const url = type === 'admin' ?
`${baseUrl}/api/requests/ws/admin` :
`${baseUrl}/api/requests/ws/employee/${id}`
console.log('Connecting to WebSocket:', url)
if (this.socket) {
console.log('Closing existing connection')
this.socket.close()
}
this.socket = new WebSocket(url)
this.socket.onopen = () => {
@@ -26,8 +38,13 @@ class WebSocketClient {
}
this.socket.onmessage = (event) => {
const data = JSON.parse(event.data)
this.messageHandlers.forEach(handler => handler(data))
console.log('WebSocket message received:', event.data)
try {
const data = JSON.parse(event.data)
this.messageHandlers.forEach(handler => handler(data))
} catch (error) {
console.error('Error parsing WebSocket message:', error)
}
}
this.socket.onclose = () => {
@@ -43,12 +60,12 @@ class WebSocketClient {
}
private tryReconnect() {
if (this.reconnectAttempts < this.maxReconnectAttempts) {
if (this.reconnectAttempts < this.maxReconnectAttempts && this.currentType) {
this.reconnectAttempts++
console.log(`Attempting to reconnect (${this.reconnectAttempts}/${this.maxReconnectAttempts})`)
setTimeout(() => {
console.log(`Attempting to reconnect (${this.reconnectAttempts}/${this.maxReconnectAttempts})`)
this.connect('admin')
}, this.reconnectTimeout)
this.connect(this.currentType!, this.currentId)
}, this.reconnectTimeout * this.reconnectAttempts)
}
}
@@ -68,6 +85,9 @@ class WebSocketClient {
this.socket.close()
this.socket = null
}
this.currentType = null
this.currentId = undefined
this.isConnected.value = false
}
}

View File

@@ -2,6 +2,11 @@
<div class="p-6">
<div class="mb-6">
<h1 class="text-2xl font-bold mb-4">Панель администратора</h1>
<div class="mb-4">
<span :class="wsClient.isConnected ? 'text-green-600' : 'text-red-600'">
{{ wsClient.isConnected ? 'WebSocket подключен' : 'WebSocket отключен' }}
</span>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
<div class="bg-white p-4 rounded-lg shadow">
<h3 class="text-lg font-semibold mb-2">Новые заявки</h3>
@@ -94,6 +99,8 @@ const fetchData = async () => {
// Обработчик WebSocket сообщений
const handleWebSocketMessage = async (data: any) => {
console.log('Received WebSocket message:', data)
if (data.type === 'new_request') {
try {
// Получаем актуальную статистику
@@ -127,8 +134,11 @@ const handleWebSocketMessage = async (data: any) => {
// Подключение к WebSocket при монтировании компонента
onMounted(() => {
fetchData()
wsClient.connect('admin')
wsClient.addMessageHandler(handleWebSocketMessage)
// Добавляем небольшую задержку перед подключением WebSocket
setTimeout(() => {
wsClient.connect('admin')
wsClient.addMessageHandler(handleWebSocketMessage)
}, 1000)
})
// Отключение от WebSocket при размонтировании компонента