You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
96 lines
3.0 KiB
96 lines
3.0 KiB
/** Translates between websocket messages and Commands. */
|
|
import {ClientCommand} from "../actions/ClientAction";
|
|
import {
|
|
SERVER_GOODBYE,
|
|
SERVER_SOCKET_STARTUP,
|
|
ServerCommand,
|
|
ServerGoodbyeCommand,
|
|
ServerSocketStartupAction,
|
|
SocketState
|
|
} from "../actions/ServerAction";
|
|
|
|
class WebsocketTranslator {
|
|
readonly url: string
|
|
readonly protocols: readonly string[]
|
|
readonly onStartup: (startup: ServerSocketStartupAction) => void
|
|
readonly onMessage: (command: ServerCommand) => void
|
|
readonly onGoodbye: (goodbye: ServerGoodbyeCommand) => void
|
|
private socket: WebSocket|null
|
|
|
|
constructor({
|
|
url,
|
|
protocols,
|
|
onStartup,
|
|
onMessage,
|
|
onGoodbye
|
|
}: {
|
|
url: string,
|
|
protocols: readonly string[],
|
|
onStartup: (startup: ServerSocketStartupAction) => void,
|
|
onMessage: (command: ServerCommand) => void,
|
|
onGoodbye: (goodbye: ServerGoodbyeCommand) => void
|
|
}) {
|
|
this.url = url
|
|
this.protocols = protocols.slice()
|
|
this.onStartup = onStartup
|
|
this.onMessage = onMessage
|
|
this.onGoodbye = onGoodbye
|
|
this.socket = null
|
|
}
|
|
|
|
connect() {
|
|
if (this.socket != null) {
|
|
throw Error("Already running")
|
|
}
|
|
this.socket = new WebSocket(this.url, this.protocols.slice())
|
|
this.socket.addEventListener("open", this.handleOpen)
|
|
this.socket.addEventListener("message", this.handleMessage)
|
|
this.socket.addEventListener("close", this.handleClose)
|
|
this.socket.addEventListener("error", WebsocketTranslator.handleError)
|
|
this.onStartup({
|
|
type: SERVER_SOCKET_STARTUP,
|
|
state: SocketState.CONNECTING,
|
|
})
|
|
}
|
|
|
|
send(message: ClientCommand) {
|
|
// TODO: Protoitize the client message and send() it.
|
|
}
|
|
|
|
close(code: number, reason: string) {
|
|
this.socket?.close(code, reason)
|
|
}
|
|
|
|
private handleOpen(e: Event) {
|
|
this.onStartup({
|
|
type: SERVER_SOCKET_STARTUP,
|
|
state: SocketState.OPEN,
|
|
})
|
|
}
|
|
|
|
private handleMessage(e: MessageEvent) {
|
|
// TODO: Parse the server message and pass it to onMessage.
|
|
}
|
|
|
|
private handleClose(e: CloseEvent) {
|
|
this.onGoodbye({
|
|
type: SERVER_GOODBYE,
|
|
code: e.code,
|
|
reason: e.reason,
|
|
currentTime: new Date(),
|
|
})
|
|
this.clearSocket()
|
|
}
|
|
|
|
private static handleError(e: Event) {
|
|
console.log("Websocket error: ", e)
|
|
}
|
|
|
|
private clearSocket() {
|
|
this.socket?.removeEventListener("open", this.handleOpen)
|
|
this.socket?.removeEventListener("message", this.handleMessage)
|
|
this.socket?.removeEventListener("close", this.handleClose)
|
|
this.socket?.removeEventListener("error", WebsocketTranslator.handleError)
|
|
this.socket = null
|
|
}
|
|
} |