( req: http.IncomingMessage, socket: net.Socket, )
| 228 | } |
| 229 | |
| 230 | export function upgradeToWebSocket( |
| 231 | req: http.IncomingMessage, |
| 232 | socket: net.Socket, |
| 233 | ): WebSocketConnection { |
| 234 | const key = req.headers["sec-websocket-key"]; |
| 235 | if (!key) { |
| 236 | socket.write("HTTP/1.1 400 Bad Request\r\n\r\n"); |
| 237 | socket.destroy(); |
| 238 | throw new Error("Missing Sec-WebSocket-Key header"); |
| 239 | } |
| 240 | |
| 241 | const acceptKey = computeAcceptKey(key); |
| 242 | |
| 243 | let responseHeaders = |
| 244 | "HTTP/1.1 101 Switching Protocols\r\n" + |
| 245 | "Upgrade: websocket\r\n" + |
| 246 | "Connection: Upgrade\r\n" + |
| 247 | `Sec-WebSocket-Accept: ${acceptKey}\r\n`; |
| 248 | |
| 249 | // Echo back requested subprotocol if present |
| 250 | const protocol = req.headers["sec-websocket-protocol"]; |
| 251 | if (protocol) { |
| 252 | // Take the first offered protocol |
| 253 | const first = protocol.split(",")[0].trim(); |
| 254 | responseHeaders += `Sec-WebSocket-Protocol: ${first}\r\n`; |
| 255 | } |
| 256 | |
| 257 | responseHeaders += "\r\n"; |
| 258 | |
| 259 | socket.write(responseHeaders); |
| 260 | |
| 261 | return new WebSocketConnection(socket); |
| 262 | } |
searching dependent graphs…