mirror of
https://code.equilibrium.co.ao/ITO/doneit-web.git
synced 2026-04-20 05:16:07 +00:00
connect to socket server
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
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}`);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user