mirror of
https://github.com/linux-odyssey/linux-odyssey.git
synced 2026-11-06 03:20:13 +08:00
refactor: use SocketWrapper to wrap the instance
This commit is contained in:
1 parent
313d30edda
commit
5d9951a3a2
5 files changed
+75
-38
No files matched your search
@@ -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()
|
||||
Reference in new issue
Block a user