Skip to content

Instantly share code, notes, and snippets.

@timetocode
Created December 20, 2016 07:48
Show Gist options
  • Save timetocode/68616a0a5f7240dd9bcf6050a582501b to your computer and use it in GitHub Desktop.
Save timetocode/68616a0a5f7240dd9bcf6050a582501b to your computer and use it in GitHub Desktop.
A node-based proxy server example. Here 8 game servers are listening for websocket connections (ports 8000-8007), a file server that serves the game's assests is listening on 7999, and a small app that creates a list of the servers is running on 8080. Externally all of these services are exposed on port 80 and different urls. /0 through /7 are t…
var http = require('http')
var httpProxy = require('http-proxy')
var servers = {
'/0': 'ws://127.0.0.1:8000',
'/1': 'ws://127.0.0.1:8001',
'/2': 'ws://127.0.0.1:8002',
'/3': 'ws://127.0.0.1:8003',
'/4': 'ws://127.0.0.1:8004',
'/5': 'ws://127.0.0.1:8005',
'/6': 'ws://127.0.0.1:8006',
'/7': 'ws://127.0.0.1:8007',
}
var proxy = httpProxy.createProxyServer({})
proxy.on('error', (err, req, res) => {
console.log('err', err)
})
var server = http.createServer((req, res) => {
if (req.url === '/servers') {
// to the master server list api
req.url = '/'
proxy.web(req, res, { target: 'http://127.0.0.1:8080' })
} else {
// everything else to the static file server
proxy.web(req, res, { target: 'http://127.0.0.1:7999' })
}
})
server.on('upgrade', (req, socket, head) => {
// to the websocket game servers! (the ones in the servers array)
proxy.ws(req, socket, head, { target: servers[req.url] })
})
server.listen(80)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment