Created
February 23, 2021 09:20
-
-
Save exyi/ecb8ed41b520e11f1b44f00ea8d2d0e7 to your computer and use it in GitHub Desktop.
websocket basic client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <reference path="../node_modules/lz-string/typings/lz-string.d.ts" /> | |
import * as P from './protocol' | |
const endpoint = `ws://${window.location.host}/ws/` | |
let conn : WebSocket | undefined; | |
let active = false | |
let logged = false | |
export type LoginOptions = { | |
token: string, | |
errorCallback: (err: string, connectionEnds: boolean) => void | |
reconnectingCallback: (connectionReconnecting: boolean) => void | |
}; | |
const sendObject = (msg: any) => { | |
conn!.send(compressMessage(JSON.stringify(msg))) | |
} | |
const login = (token: LoginOptions) => { | |
let l : P.Login = { token: token.token } | |
sendObject(l) | |
} | |
const setupConn = (conn: WebSocket, token: LoginOptions) => { | |
active = false | |
conn.onopen = () => { | |
token.reconnectingCallback() | |
console.log("WS Connected") | |
login(token) | |
} | |
conn.onclose = () => { | |
console.log("WS Disconnected") | |
active = false | |
... show error modal (with reconnect button) | |
} | |
conn.onerror = ev => { | |
console.warn("WS error: ", ev) | |
... show error modal (with reconnect button) | |
} | |
conn.onmessage = ev => { | |
const obj = JSON.parse(decodeMessage(ev.data)) | |
if ("error" in obj) { | |
const err = obj.error.error || obj.error | |
... process "user-error" | |
} | |
else if (!active) { | |
logged = active = true | |
const msg = obj as P.LoginrData | |
token.censorCallback.loginData(msg, sendObject); | |
} else { | |
const msg = obj as P.Server2Client | |
process msg | |
} | |
} | |
} | |
export const reconnect = (token: LoginOptions) => { | |
if (conn && conn.readyState != WebSocket.CLOSED && conn.readyState != WebSocket.CLOSING) { | |
return | |
} | |
if (!navigator.onLine) { | |
... offline modal | |
} | |
conn = new WebSocket(endpoint) | |
setupConn(conn, token) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment