Skip to content

Instantly share code, notes, and snippets.

@nicokaiser
Created September 15, 2011 12:54
Show Gist options
  • Save nicokaiser/1219165 to your computer and use it in GitHub Desktop.
Save nicokaiser/1219165 to your computer and use it in GitHub Desktop.
WebSocket library fallback for old protocol clients
#!/usr/bin/env node
// Example of how to fallback to alternative websocket library for old protocol clients
// see https://gist.github.com/1148686
var http = require('http'),
WebSocketRequest = require('websocket').request,
ws = require('websocket-server');
var httpServer = http.createServer(function(request, response) {
console.log((new Date()) + " Received request for " + request.url);
response.writeHead(404);
response.end();
});
httpServer.listen(10080, function() {
console.log((new Date()) + " Server is listening on port 10080");
});
// node-websocket-server
var miksagoConnection = require('./node_modules/websocket-server/lib/ws/connection');
var miksagoServer = ws.createServer();
miksagoServer.server = httpServer;
miksagoServer.addListener('connection', function(connection) {
// Add remoteAddress property
connection.remoteAddress = connection._socket.remoteAddress;
// We want to use "sendUTF" regardless of the server implementation
connection.sendUTF = connection.send;
handleConnection(connection);
});
// WebSocket-Node config
var wsServerConfig = {
// All options *except* 'httpServer' are required when bypassing
// WebSocketServer.
maxReceivedFrameSize: 0x10000,
maxReceivedMessageSize: 0x100000,
fragmentOutgoingMessages: true,
fragmentationThreshold: 0x4000,
keepalive: true,
keepaliveInterval: 20000,
assembleFragments: true,
// autoAcceptConnections is not applicable when bypassing WebSocketServer
// autoAcceptConnections: false,
disableNagleAlgorithm: true,
closeTimeout: 5000
};
// Handle the upgrade event ourselves instead of using WebSocketServer
httpServer.on('upgrade', function(req, socket, head) {
if (typeof req.headers['sec-websocket-version'] !== 'undefined') {
// WebSocket hybi-08/-09/-10 connection (WebSocket-Node)
var wsRequest = new WebSocketRequest(socket, req, wsServerConfig);
try {
wsRequest.readHandshake();
var wsConnection = wsRequest.accept(wsRequest.requestedProtocols[0], wsRequest.origin);
handleConnection(wsConnection);
}
catch(e) {
console.log("WebSocket Request unsupported by WebSocket-Node: " + e.toString());
return;
}
} else {
// WebSocket hixie-75/-76/hybi-00 connection (node-websocket-server)
if (req.method === 'GET' &&
(req.headers.upgrade && req.headers.connection) &&
req.headers.upgrade.toLowerCase() === 'websocket' &&
req.headers.connection.toLowerCase() === 'upgrade') {
new miksagoConnection(miksagoServer.manager, miksagoServer.options, req, socket, head);
}
}
});
// A common connection handler
function handleConnection(connection) {
console.log((new Date()) + " Connection accepted.");
connection.addListener('message', function(wsMessage) {
var message = wsMessage;
// WebSocket-Node adds a "type", node-websocket-server does not
if (typeof wsMessage.type !== 'undefined') {
if (wsMessage.type !== 'utf8') {
return;
}
message = wsMessage.utf8Data;
}
console.log("Received Message: " + message);
connection.sendUTF(message);
});
connection.addListener('close', function() {
console.log((new Date()) + " Peer " + connection.remoteAddress + " disconnected.");
});
}
@theturtle32
Copy link

theturtle32 commented Dec 2, 2011 via email

@toshirot
Copy link

toshirot commented Dec 4, 2011

I forked:) https://gist.github.com/1428579
Best regards

@theturtle32
Copy link

Thanks, updated the README on the WebSocket-Node page.

@wcauchois
Copy link

Hey, thanks for this! If anyone's interested, I turned this code into a library that emulates the node-websocket-server API but under the hood uses whichever implementation is appropriate. Feel free to check it out here: https://github.com/wcauchois/websocket-fallback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment