Skip to content

Commit 441642e

Browse files
sapphi-redbluwy
authored andcommitted
fix: ws never connects after restarting server if server.hmr.server is set (#14127)
1 parent 0f582bf commit 441642e

File tree

1 file changed

+15
-3
lines changed
  • packages/vite/src/node/server

1 file changed

+15
-3
lines changed

packages/vite/src/node/server/ws.ts

+15-3
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import path from 'node:path'
2-
import type { Server } from 'node:http'
2+
import type { IncomingMessage, Server } from 'node:http'
33
import { STATUS_CODES, createServer as createHttpServer } from 'node:http'
44
import type { ServerOptions as HttpsServerOptions } from 'node:https'
55
import { createServer as createHttpsServer } from 'node:https'
66
import type { Socket } from 'node:net'
7+
import type { Duplex } from 'node:stream'
78
import colors from 'picocolors'
89
import type { WebSocket as WebSocketRaw } from 'ws'
910
import { WebSocketServer as WebSocketServerRaw_ } from 'ws'
@@ -104,6 +105,11 @@ export function createWebSocketServer(
104105
// TODO: the main server port may not have been chosen yet as it may use the next available
105106
const portsAreCompatible = !hmrPort || hmrPort === config.server.port
106107
const wsServer = hmrServer || (portsAreCompatible && server)
108+
let hmrServerWsListener: (
109+
req: InstanceType<typeof IncomingMessage>,
110+
socket: Duplex,
111+
head: Buffer,
112+
) => void
107113
const customListeners = new Map<string, Set<WebSocketCustomListener<any>>>()
108114
const clientsMap = new WeakMap<WebSocketRaw, WebSocketClient>()
109115
const port = hmrPort || 24678
@@ -116,7 +122,7 @@ export function createWebSocketServer(
116122
hmrBase = path.posix.join(hmrBase, hmrPath)
117123
}
118124
wss = new WebSocketServerRaw({ noServer: true })
119-
wsServer.on('upgrade', (req, socket, head) => {
125+
hmrServerWsListener = (req, socket, head) => {
120126
if (
121127
req.headers['sec-websocket-protocol'] === HMR_HEADER &&
122128
req.url === hmrBase
@@ -125,7 +131,8 @@ export function createWebSocketServer(
125131
wss.emit('connection', ws, req)
126132
})
127133
}
128-
})
134+
}
135+
wsServer.on('upgrade', hmrServerWsListener)
129136
} else {
130137
// http server request handler keeps the same with
131138
// https://github.com/websockets/ws/blob/45e17acea791d865df6b255a55182e9c42e5877a/lib/websocket-server.js#L88-L96
@@ -273,6 +280,11 @@ export function createWebSocketServer(
273280
},
274281

275282
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+
}
276288
return new Promise((resolve, reject) => {
277289
wss.clients.forEach((client) => {
278290
client.terminate()

0 commit comments

Comments
 (0)