106 lines
2.7 KiB
TypeScript
Raw Normal View History

2022-12-01 22:26:41 +08:00
import Singleton from '../Base/Singleton'
2022-12-03 20:06:57 +08:00
import { IModel } from '../Common';
2022-12-01 22:26:41 +08:00
const TIMEOUT = 5000
2022-12-03 20:06:57 +08:00
export interface ICallApiRet<T> {
2022-12-01 22:26:41 +08:00
success: boolean;
error?: Error;
2022-12-03 20:06:57 +08:00
res?: T
2022-12-01 22:26:41 +08:00
}
2022-12-03 20:06:57 +08:00
type aaa = keyof IModel
2022-12-01 22:26:41 +08:00
export default class NetworkManager extends Singleton {
static get Instance() {
return super.GetInstance<NetworkManager>()
}
ws: WebSocket
port = 8888
cbs: Map<string, Function[]> = new Map()
isConnected = false
connect() {
return new Promise((resolve, reject) => {
this.ws = new WebSocket(`ws://localhost:${this.port}`)
this.ws.onopen = () => {
console.log("ws onopen")
this.isConnected = true
resolve(true)
}
this.ws.onerror = () => {
this.isConnected = false
reject("ws onerror")
}
this.ws.onclose = () => {
this.isConnected = false
reject("ws onclose")
}
this.ws.onmessage = (e) => {
try {
const json = JSON.parse(e.data)
const { name, data } = json
try {
if (this.cbs.has(name) && this.cbs.get(name).length) {
console.log(json);
this.cbs.get(name).forEach(cb => cb(data))
}
} catch (error) {
console.log("this.cbs.get(name).forEach(cb => cb(restData))", error)
}
} catch (error) {
console.log('解析失败不是合法的JSON格式', error)
}
}
})
}
2022-12-03 20:06:57 +08:00
callApi<T extends keyof IModel['api']>(name: T, data: IModel['api'][T]['req']): Promise<ICallApiRet<IModel['api'][T]['res']>> {
return new Promise((resolve) => {
2022-12-01 22:26:41 +08:00
try {
// 超时处理
const timer = setTimeout(() => {
resolve({ success: false, error: new Error('timeout') })
this.unlistenMsg(name, cb)
}, TIMEOUT)
// 回调处理
2022-12-03 20:06:57 +08:00
const cb = (res) => {
2022-12-01 22:26:41 +08:00
resolve(res)
clearTimeout(timer)
this.unlistenMsg(name, cb)
}
2022-12-03 20:06:57 +08:00
this.listenMsg(name as any, cb)
2022-12-01 22:26:41 +08:00
this.ws.send(JSON.stringify({ name, data }))
} catch (error) {
console.log(error)
resolve({ success: false, error: error as Error })
}
})
}
2022-12-03 20:06:57 +08:00
sendMsg<T extends keyof IModel['msg']>(name: T, data: IModel['msg'][T]) {
this.ws.send(JSON.stringify({ name, data }))
}
listenMsg<T extends keyof IModel['msg']>(name: T, cb: (args: IModel['msg'][T]) => void) {
if (this.cbs.has(name)) {
this.cbs.get(name).push(cb)
} else {
this.cbs.set(name, [cb])
}
}
unlistenMsg(name: string, cb: Function) {
if (this.cbs.has(name)) {
const index = this.cbs.get(name).indexOf(cb)
index > -1 && this.cbs.get(name).splice(index, 1)
}
}
2022-12-01 22:26:41 +08:00
}