Skip to content

Instantly share code, notes, and snippets.

@tehbeard
Created October 6, 2015 12:59
Show Gist options
  • Save tehbeard/c5405d3acac3fb3da701 to your computer and use it in GitHub Desktop.
Save tehbeard/c5405d3acac3fb3da701 to your computer and use it in GitHub Desktop.
node ws->express passthrough
var httpServer = http.createServer(app);
var ServerResponse = http.ServerResponse;
var wsServer = new WebSocketServer({ server: httpServer });
wsServer.on('connection', function(ws) {
var response = new ServerResponse(ws.upgradeReq);
response.writeHead = function (statusCode) {
if (statusCode > 200) ws.close();
}; //Construct response that will kill the websocket.
var sockHandled = false;
ws.upgradeReq.getWebSocket = function(){ //Wrap socket in function to check if it's accessed.
sockHandled = true;
return ws;
};
app.handle(ws.upgradeReq, response, function() { //Pass to Express, and check if handled, if not, kill the socket.
if (!sockHandled) {
ws.close();
}
});
});
httpServer.listen(8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment