This commit is contained in:
Peter Maquiran
2021-08-18 18:58:28 +01:00
parent 00a18300e4
commit e0e258ab62
3 changed files with 91 additions and 0 deletions
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { SynchroService } from './synchro.service';
describe('SynchroService', () => {
let service: SynchroService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(SynchroService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
@@ -0,0 +1,74 @@
import { Injectable } from '@angular/core';
import { v4 as uuidv4 } from 'uuid'
export interface wss{
url: string,
type: 'reflect' | 'emit'
header: {
id: string
bluePrint: string,
jwt: string
}
}
@Injectable({
providedIn: 'root'
})
export class SynchroService {
[x: string]: any;
private connection!: WebSocket;
private id: string = uuidv4();
public conected = false
private url: string = ''
constructor(){}
setUrl(wss:wss) {
this.url = `${wss.url}${wss.header.id}/${wss.header.jwt}/${wss.header.bluePrint}/${this.id}/`
}
connect() {
this.connection = new WebSocket(this.url);
// bind function
this.connection.onopen = this.onopen;
this.connection.onmessage = this.onmessage;
this.connection.onclose = this.onclose;
this.connection.onerror = this.onerror;
}
private onopen = () =>{
console.log('open ======================= welcome to socket server')
// this.connection.send(JSON.stringify({user:'user1'}));
}
public $send = (object: any) => {
let sendData = JSON.stringify(Object.assign({}, object));
this.connection.send(sendData);
}
private onmessage = async (event: any)=> {
}
private onclose=(event:any)=>{
setTimeout(() => {
if (event.wasClean) {
console.log(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
} else {
// e.g. server process killed or network down
// event.code is usually 1006 in this case
console.log('[close] Connection died');
console.log('Reconnect')
this.connect()
}
}, 100);
}
private onerror=(event: any)=>{
console.log(`[error] ${event.message}`);
}
}