Files
doneit-web/src/app/services/socket/synchro.service.ts
T

101 lines
2.0 KiB
TypeScript
Raw Normal View History

2021-08-18 18:58:28 +01:00
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 = ''
2021-08-19 09:10:38 +01:00
callback = function(){}
2021-08-18 18:58:28 +01:00
constructor(){}
2021-08-19 09:10:38 +01:00
setUrl() {
let header ={
id:'1234',
bluePrint: '12312123',
jwt: uuidv4()
}
let wss: wss ={
header,
url: 'wss://synchro-server.herokuapp.com/ws/some_url/',
type: 'reflect'
}
2021-08-18 18:58:28 +01:00
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')
2021-08-19 09:10:38 +01:00
2021-08-18 18:58:28 +01:00
}
2021-08-19 09:10:38 +01:00
public $send(object: any) {
let message = {
message: '{"person.adress.country":"1Angola"}',
username: '',
idConnection: this.id
}
let sendData = JSON.stringify(Object.assign({}, message));
2021-08-18 18:58:28 +01:00
this.connection.send(sendData);
}
private onmessage = async (event: any)=> {
2021-08-19 09:10:38 +01:00
this.callback()
2021-08-18 18:58:28 +01:00
}
2021-08-19 09:10:38 +01:00
private onclose=(event:any)=> {
2021-08-18 18:58:28 +01:00
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}`);
}
}
2021-08-19 09:10:38 +01:00
export const connection = new SynchroService()
connection.setUrl()
connection.connect()