mirror of
https://code.equilibrium.co.ao/ITO/doneit-web.git
synced 2026-04-20 05:16:07 +00:00
56 lines
1.2 KiB
TypeScript
56 lines
1.2 KiB
TypeScript
|
|
import { Injectable } from '@angular/core';
|
||
|
|
|
||
|
|
@Injectable({
|
||
|
|
providedIn: 'root'
|
||
|
|
})
|
||
|
|
export class SocketInterfaceService {
|
||
|
|
|
||
|
|
private socket!: WebSocket;
|
||
|
|
private url = ''
|
||
|
|
private connected = false
|
||
|
|
private callBacks: {
|
||
|
|
type: 'Offline' | 'Online' | 'Onmessage' | 'Chat' | 'Notification' | 'Notifications' | '',
|
||
|
|
object?: string
|
||
|
|
funx: Function
|
||
|
|
}[] = []
|
||
|
|
private msgQueue = []
|
||
|
|
|
||
|
|
constructor() { }
|
||
|
|
|
||
|
|
connect(url) {
|
||
|
|
|
||
|
|
this.url = url
|
||
|
|
this.socket = new WebSocket(this.url);
|
||
|
|
// bind function
|
||
|
|
this.socket.onopen = this.onopen;
|
||
|
|
this.socket.onmessage = this.onmessage;
|
||
|
|
this.socket.onclose = this.onclose;
|
||
|
|
this.socket.onerror = this.onerror;
|
||
|
|
}
|
||
|
|
|
||
|
|
send(message: object) {
|
||
|
|
if (!this.connected) { // save data to send when back online
|
||
|
|
this.msgQueue.push(message)
|
||
|
|
} else {
|
||
|
|
let messageStr = JSON.stringify(message)
|
||
|
|
this.socket.send(messageStr)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
onopen() {
|
||
|
|
|
||
|
|
}
|
||
|
|
onmessage() {}
|
||
|
|
|
||
|
|
onclose(event: any) {
|
||
|
|
console.log(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
|
||
|
|
setTimeout(()=>{
|
||
|
|
this.connect(this.url)
|
||
|
|
}, 500)
|
||
|
|
}
|
||
|
|
|
||
|
|
onerror = (event: any) => {
|
||
|
|
console.log(`[error] ${event.message}`);
|
||
|
|
}
|
||
|
|
}
|