Created
February 17, 2024 09:33
-
-
Save nitedani/3848f253551e311a650a0a38cf6e3754 to your computer and use it in GitHub Desktop.
Pure node simple websocket proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function setupWsProxy(server: http.Server) { | |
server.on('upgrade', (clientReq, clientSocket) => { | |
const req_ = http.request({ | |
port: remotePort, | |
host: remoteHost, | |
headers: clientReq.headers | |
}) | |
req_.end() | |
req_.on('upgrade', (remoteResponse, remoteSocket) => { | |
const head_ = [ | |
'HTTP/1.1 101 Switching Protocols', | |
...Object.entries(remoteResponse.headers).map(([key, value]) => `${key}: ${value}`), | |
'' | |
] | |
.map((line) => line.concat('\r\n')) | |
.join('') | |
clientSocket.write(head_) | |
clientSocket.pipe(remoteSocket) | |
remoteSocket.pipe(clientSocket) | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment