connect to socket server

This commit is contained in:
Peter Maquiran
2022-01-07 09:03:15 +01:00
parent 73354e00af
commit 6e0b54c0cf
6 changed files with 185 additions and 3 deletions
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { SocketInterfaceService } from './socket-interface.service';
describe('SocketInterfaceService', () => {
let service: SocketInterfaceService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(SocketInterfaceService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
@@ -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}`);
}
}