refactor: use SocketWrapper to wrap the instance

This commit is contained in:
wancat committed 2023-08-18 21:19:11 +08:00
1 parent 313d30edda
commit 5d9951a3a2
5 files changed
+75 -38

No files matched your search

+52
View File
@@ -0,0 +1,52 @@
import io from 'socket.io-client'
const host = 'wss://odyssey.wancat.cc'
class SocketWrapper {
constructor() {
this.socket = null
this.listeners = []
}
connect(session) {
if (this.socket) {
this.socket.off()
this.socket.disconnect()
}
this.socket = io(host, {
query: {
session_id: session._id,
},
})
this.socket.on('connect', () => {
console.log('Socket connected to session', session._id)
})
this.reconnect()
}
on(event, callback) {
this.listeners.push({ event, callback })
if (this.socket) {
this.socket.on(event, callback)
}
}
reconnect() {
this.listeners.forEach(({ event, callback }) => {
this.socket.on(event, callback)
})
}
send(data) {
this.socket.send(data)
}
emit(event, data) {
this.socket.emit(event, data)
}
}
export default new SocketWrapper()