1
1
import path from 'node:path'
2
- import type { Server } from 'node:http'
2
+ import type { IncomingMessage , Server } from 'node:http'
3
3
import { STATUS_CODES , createServer as createHttpServer } from 'node:http'
4
4
import type { ServerOptions as HttpsServerOptions } from 'node:https'
5
5
import { createServer as createHttpsServer } from 'node:https'
6
6
import type { Socket } from 'node:net'
7
+ import type { Duplex } from 'node:stream'
7
8
import colors from 'picocolors'
8
9
import type { WebSocket as WebSocketRaw } from 'ws'
9
10
import { WebSocketServer as WebSocketServerRaw_ } from 'ws'
@@ -104,6 +105,11 @@ export function createWebSocketServer(
104
105
// TODO: the main server port may not have been chosen yet as it may use the next available
105
106
const portsAreCompatible = ! hmrPort || hmrPort === config . server . port
106
107
const wsServer = hmrServer || ( portsAreCompatible && server )
108
+ let hmrServerWsListener : (
109
+ req : InstanceType < typeof IncomingMessage > ,
110
+ socket : Duplex ,
111
+ head : Buffer ,
112
+ ) => void
107
113
const customListeners = new Map < string , Set < WebSocketCustomListener < any > > > ( )
108
114
const clientsMap = new WeakMap < WebSocketRaw , WebSocketClient > ( )
109
115
const port = hmrPort || 24678
@@ -116,7 +122,7 @@ export function createWebSocketServer(
116
122
hmrBase = path . posix . join ( hmrBase , hmrPath )
117
123
}
118
124
wss = new WebSocketServerRaw ( { noServer : true } )
119
- wsServer . on ( 'upgrade' , ( req , socket , head ) => {
125
+ hmrServerWsListener = ( req , socket , head ) => {
120
126
if (
121
127
req . headers [ 'sec-websocket-protocol' ] === HMR_HEADER &&
122
128
req . url === hmrBase
@@ -125,7 +131,8 @@ export function createWebSocketServer(
125
131
wss . emit ( 'connection' , ws , req )
126
132
} )
127
133
}
128
- } )
134
+ }
135
+ wsServer . on ( 'upgrade' , hmrServerWsListener )
129
136
} else {
130
137
// http server request handler keeps the same with
131
138
// https://github.com/websockets/ws/blob/45e17acea791d865df6b255a55182e9c42e5877a/lib/websocket-server.js#L88-L96
@@ -273,6 +280,11 @@ export function createWebSocketServer(
273
280
} ,
274
281
275
282
close ( ) {
283
+ // should remove listener if hmr.server is set
284
+ // otherwise the old listener swallows all WebSocket connections
285
+ if ( hmrServerWsListener && wsServer ) {
286
+ wsServer . off ( 'upgrade' , hmrServerWsListener )
287
+ }
276
288
return new Promise ( ( resolve , reject ) => {
277
289
wss . clients . forEach ( ( client ) => {
278
290
client . terminate ( )
0 commit comments