Created
August 17, 2013 23:46
-
-
Save verma/6259211 to your computer and use it in GitHub Desktop.
A simple proxied websocket server example
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
// app.js | |
// A simple proxying example | |
// | |
// Setup websocket server on port 19000 | |
// Setup proxy on port 9000 to proxy to 19000 | |
// Make a websocket request to 9000 | |
// | |
var WebSocket = require('ws'), | |
WebSocketServer = WebSocket.Server, | |
proxy = require('http-proxy'); | |
// goes in a loop sending messages to the server as soon as | |
// the servers are setup | |
var triggerClient = function() { | |
var ws = new WebSocket('ws://localhost:9090/'); | |
ws.on('open', function() { | |
console.log('ws: connection open'); | |
setInterval(function() { | |
ws.send("Hello"); | |
}, 1000); | |
}); | |
ws.on('message', function(data) { | |
console.log('ws: got ' + data); | |
}); | |
} | |
// setup websocket server and a proxy | |
// | |
var go = function() { | |
// setup a websocket server on port 19000 | |
// | |
var wss = new WebSocketServer({ port: 19000 }); | |
wss.on('connection', function(ws) { | |
console.log('wss: got connection'); | |
ws.on('message', function(data) { | |
console.log('wss: got ' + data); | |
ws.send('wss response: ' + data); | |
}); | |
}); | |
// setup a proxy server | |
var server = proxy.createServer(function (req, res, proxy) { | |
proxy.proxyRequest(req, res, { | |
host: 'localhost', | |
port: 19000 | |
}); | |
}); | |
server.on('upgrade', function (req, socket, head) { | |
console.log('proxy: got upgrade, proxying web request'); | |
server.proxy.proxyWebSocketRequest(req, socket, head, { | |
host: 'localhost', | |
port: 19000 | |
}); | |
}); | |
server.listen(9090, triggerClient); | |
}; | |
process.nextTick(go); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment