-
-
Notifications
You must be signed in to change notification settings - Fork 580
/
io.worker.ts
115 lines (94 loc) 路 2.27 KB
/
io.worker.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import { io } from 'socket.io-client'
import type { Socket } from 'socket.io-client'
/* eslint-disable no-console */
/// <reference lib="webworker" />
let ws: Socket | null = null
function setupIo(config: { url: string }) {
if (ws) return
// 浣跨敤 socket.io
console.log('Connecting to io, url: ', config.url)
ws = io(config.url, {
timeout: 10000,
reconnectionDelay: 3000,
autoConnect: false,
reconnectionAttempts: 3,
transports: ['websocket'],
})
if (!ws) return
ws.on('disconnect', () => {
boardcast({
type: 'disconnect',
})
})
/**
* @param {any} payload
*/
ws.on('message', (payload) => {
console.log('ws', payload)
boardcast({
type: 'message',
payload,
})
})
ws.on('connect', () => {
console.log('Connected to ws.io server from SharedWorker')
if (waitingEmitQueue.length > 0) {
waitingEmitQueue.forEach((payload) => {
if (!ws) return
ws.emit('message', payload)
})
waitingEmitQueue.length = 0
}
boardcast({
type: 'connect',
// @ts-expect-error
payload: ws.id,
})
})
ws.open()
boardcast({
type: 'sid',
payload: ws.id,
})
}
const ports = [] as MessagePort[]
self.addEventListener('connect', (ev: any) => {
const event = ev as MessageEvent
const port = event.ports[0]
ports.push(port)
port.onmessage = (event) => {
const { type, payload } = event.data
console.log('get message from main', event.data)
switch (type) {
case 'config':
setupIo(payload)
break
case 'emit':
if (ws) {
if (ws.connected) ws.emit('message', payload)
else waitingEmitQueue.push(payload)
}
break
case 'reconnect':
if (ws) ws.open()
break
case 'init':
port.postMessage({ type: 'ping' })
if (ws) {
if (ws.connected) port.postMessage({ type: 'connect' })
port.postMessage({ type: 'sid', payload: ws.id })
}
break
default:
console.log('Unknown message type:', type)
}
}
port.start()
})
function boardcast(payload: any) {
console.log('[ws] boardcast', payload)
ports.forEach((port) => {
port.postMessage(payload)
})
}
const waitingEmitQueue: any[] = []