mancala/src/rtmt/rtmt_websocket.ts

82 lines
2.6 KiB
TypeScript
Raw Normal View History

2021-06-27 19:28:09 +03:00
import { decode, encode } from "./encode_decode_message"
import { Bytes, OnMessage, RTMT } from "./rtmt"
import WebSocket from "ws"
import * as http from 'http';
export class RTMTWS implements RTMT {
private messageChannels: Map<String, OnMessage>
private wsServer: WebSocket.Server | null
public clients = new Map<string, WebSocket>()
constructor() {
this.messageChannels = new Map<String, OnMessage>()
this.wsServer = null
}
2021-06-29 03:25:42 +03:00
initWebSocket(server: http.Server, onopen: (userKey : string) => any) {
2021-06-27 19:28:09 +03:00
const wsServer = new WebSocket.Server({ server })
2021-06-29 03:25:42 +03:00
this.wsServer = wsServer
2021-06-27 19:28:09 +03:00
this.clients = new Map<string, WebSocket>()
wsServer.on("connection", (ws: WebSocket, req: Request) => {
const regexResult = req.url.split(RegExp("\/\?userKey="));
const clientID = regexResult[1]
this.clients.set(clientID, ws)
ws.on("message", (messageBytes: Bytes) => {
console.log('received: %s', messageBytes);
2021-06-29 03:25:42 +03:00
this.onWebSocketMessage(clientID, messageBytes)
2021-06-27 19:28:09 +03:00
})
ws.on("close", (code: number, reason: string) => {
console.log("WS Closed! code : " + code + " reason : " + reason);
this.clients.delete(clientID)
})
ws.on("error", (err: Error) => {
console.log("WS Closed with error! error : " + err.message);
this.clients.delete(clientID)
})
2021-06-29 03:25:42 +03:00
onopen(clientID)
2021-06-27 19:28:09 +03:00
})
}
sendMessage(clientID: string, channel: string, message: Bytes) {
if (this.wsServer) {
const client = this.clients.get(clientID)
if (client) {
const data = encode({ channel: channel, data: message })
console.log("(RTMT) Sending message to channel " + channel);
client.send(data)
} else {
console.log("Client not connected!");
}
} else {
console.log('ws is undefined')
}
}
listenMessage(channel: string, callback: OnMessage) {
this.messageChannels.set(channel, callback)
}
onWebSocketMessage(clientID: string, messageBytes: Bytes) {
const message = decode(messageBytes)
this.onMessage(clientID, message.channel, message.data)
}
2021-06-29 03:25:42 +03:00
onMessage(clientID: string, channel: string, message: Bytes) {
2021-06-27 19:28:09 +03:00
const callback = this.messageChannels.get(channel)
if (callback) {
callback(clientID, message)
} else {
console.log("Channel callback not found! " + channel);
}
}
}