update socket.ts

This commit is contained in:
Chen, Tai-Lin committed 2024-03-04 23:35:05 +08:00
1 parent 4739849549
commit af9b443865
1 file changed
+11 -7
+68
View File
@@ -0,0 +1,68 @@
import io from 'socket.io-client'
class SocketWrapper {
socket: any
listeners: any
constructor() {
this.socket = null
this.listeners = []
}
connect(session: any) {
return new Promise<void>((resolve, reject) => {
this.disconnect()
this.socket = io('', {
query: {
sessionId: session._id,
},
})
this.socket.on('connect', () => {
console.log('Socket connected to session', session._id)
})
this.socket.once('terminal', () => {
resolve()
})
this.socket.on('connect_error', reject)
this.bindListeners()
})
}
on(event: any, callback: any) {
this.listeners.push({ event, callback })
if (this.socket) {
this.socket.on(event, callback)
}
}
bindListeners() {
this.listeners.forEach(
({ event, callback }: { event: any; callback: any }) => {
this.socket.on(event, callback)
}
)
}
emit(event: any, data: any) {
if (!this.socket) {
console.warn('Socket is not connected!')
return
}
this.socket.emit(event, data)
}
disconnect() {
if (this.socket) {
this.socket.off()
this.socket.disconnect()
}
}
reset() {
this.disconnect()
}
}
export default SocketWrapper