mancala/src/rtmt/rtmt_websocket.ts

70 lines
2.0 KiB
TypeScript
Raw Normal View History

2021-06-27 19:28:55 +03:00
import { decode, encode } from "./encode_decode_message"
import { OnMessage, RTMT } from "./rtmt"
import { context } from '../context';
import { wsServerAdress } from "../service/http_service";
export class RTMTWS implements RTMT{
private messageChannels : Map<String,OnMessage>
private ws : WebSocket
constructor() {
this.messageChannels = new Map<String, OnMessage>()
}
initWebSocket(onopen : ()=>any) {
context.userKeyStore.getUserKey((userKey : string)=>{
const url = wsServerAdress + '?userKey=' + userKey
const ws = new WebSocket(url)
ws.binaryType = "arraybuffer"; //for firefox
ws.onopen = () => {
console.log('ws has opened')
this.ws = ws
onopen()
}
ws.onclose = () => {
console.log('ws has closed')
//this.ws = undefined
}
ws.onmessage = (event : MessageEvent)=>{
this.onWebSocketMessage(this, event)
}
ws.addEventListener("error", ev => {
console.log({ ws_error: ev });
})
})
}
sendMessage(channel : string, message : Int8Array) {
if(this.ws === undefined){
console.log('ws is undefined')
return
}
const data = encode(channel, message)
console.log("(RTMT) Sending message to channel " + channel);
this.ws.send(data)
}
listenMessage(channel : string, callback : OnMessage) {
this.messageChannels.set(channel, callback)
}
onWebSocketMessage(rtmt : RTMTWS, event : MessageEvent) {
console.log(event);
const { channel, message } = decode(event.data)
rtmt.onMessage(channel, message)
}
onMessage(channel : string, message : Int8Array){
const callback = this.messageChannels.get(channel)
if(callback){
callback(message)
}else{
console.log("Channel callback not found!" + channel);
}
}
}