-
-
Notifications
You must be signed in to change notification settings - Fork 604
Expand file tree
/
Copy pathWebSocketServer.ts
More file actions
64 lines (54 loc) · 1.63 KB
/
WebSocketServer.ts
File metadata and controls
64 lines (54 loc) · 1.63 KB
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
import { invariant } from 'outvariant'
import { type DefaultEventMap, Emitter, TypedEvent } from 'rettime'
import fastify, { FastifyInstance } from 'fastify'
import fastifyWebSocket, { SocketStream } from '@fastify/websocket'
type FastifySocket = SocketStream['socket']
interface WebSocketEventMap extends DefaultEventMap {
connection: TypedEvent<FastifySocket>
}
export class WebSocketServer extends Emitter<WebSocketEventMap> {
private _url?: string
private app: FastifyInstance
private clients: Set<FastifySocket>
constructor() {
super()
this.clients = new Set()
this.app = fastify()
this.app.register(fastifyWebSocket)
this.app.register(async (fastify) => {
fastify.get('/', { websocket: true }, ({ socket }) => {
this.clients.add(socket)
socket.once('close', () => this.clients.delete(socket))
this.emit(new TypedEvent('connection', { data: socket }))
})
})
}
get url(): string {
invariant(
this._url,
'Failed to get "url" on WebSocketServer: server is not running. Did you forget to "await server.listen()"?',
)
return this._url
}
public async listen(port = 0): Promise<void> {
const address = await this.app.listen({
host: '127.0.0.1',
port,
})
const url = new URL(address)
url.protocol = url.protocol.replace(/^http/, 'ws')
this._url = url.href
}
public resetState(): void {
this.closeAllClients()
this.removeAllListeners()
}
public closeAllClients(): void {
this.clients.forEach((client) => {
client.close()
})
}
public async close(): Promise<void> {
return this.app.close()
}
}