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

+4 -2
View File
@@ -7,6 +7,10 @@ class SessionManager {
this.session = ref(null)
}
getSession() {
return this.session.value
}
setSession(session) {
console.log('Update session:', session)
this.session.value = session
@@ -50,6 +54,4 @@ class SessionManager {
const sessionManager = new SessionManager('helloworld')
sessionManager.lastOrCreate().catch(console.error)
export default sessionManager
+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()