-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathws.ts
56 lines (49 loc) · 1.33 KB
/
ws.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
import type { SpdyServer as Server } from '@umijs/bundler-utils';
import { chalk } from '@umijs/utils';
import { Server as HttpServer } from 'http';
import { Http2Server } from 'http2';
import { Server as HttpsServer } from 'https';
import WebSocket from '../../compiled/ws';
export function createWebSocketServer(
server: HttpServer | HttpsServer | Http2Server | Server,
port?: number | undefined,
) {
let wss: WebSocket.Server;
if (port) {
wss = new WebSocket.Server({port});
} else {
wss = new WebSocket.Server({
noServer: true,
});
}
server.on('upgrade', (req, socket, head) => {
if (req.headers['sec-websocket-protocol'] === 'webpack-hmr') {
wss.handleUpgrade(req, socket as any, head, (ws) => {
wss.emit('connection', ws, req);
});
}
});
wss.on('connection', (socket) => {
socket.send(JSON.stringify({ type: 'connected' }));
});
wss.on('error', (e: Error & { code: string }) => {
if (e.code !== 'EADDRINUSE') {
console.error(
chalk.red(`WebSocket server error:\n${e.stack || e.message}`),
);
}
});
return {
send(message: string) {
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
},
wss,
close() {
wss.close();
},
};
}