Skip to content

Instantly share code, notes, and snippets.

@jamesbjackson
Forked from theturtle32/websocket-fallback.js
Created September 23, 2011 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesbjackson/1237949 to your computer and use it in GitHub Desktop.
Save jamesbjackson/1237949 to your computer and use it in GitHub Desktop.
Example of how to fallback to alternative websocket library for old protocol clients.
#!/usr/bin/env node
var WebSocketRequest = require('websocket').request;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log((new Date()) + " Received request for " + request.url);
response.writeHead(404);
response.end();
});
server.listen(8080, function() {
console.log((new Date()) + " Server is listening on port 8080");
});
var serverConfig = {
// 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
server.on('upgrade', function(req, socket, head) {
var wsConnection;
var wsRequest = new WebSocketRequest(socket, req, serverConfig);
try {
wsRequest.readHandshake();
wsConnection = wsRequest.accept(wsRequest.requestedProtocols[0], wsRequest.origin);
// wsConnection is now live and ready for use
}
catch(e) {
console.log("WebSocket Request unsupported by WebSocket-Node: " + e.toString());
return;
// Attempt old websocket library connection here.
// wsConnection = /* some fallback code here */
}
handleWebSocketConnect(wsConnection);
});
function handleWebSocketConnect(connection) {
console.log((new Date()) + " Connection accepted.");
connection.on('message', function(message) {
if (message.type === 'utf8') {
console.log("Received Message: " + message.utf8Data);
connection.sendUTF(message.utf8Data);
}
else if (message.type === 'binary') {
console.log("Received Binary Message of " + message.binaryData.length + " bytes");
connection.sendBytes(message.binaryData);
}
});
connection.on('close', function(connection) {
console.log((new Date()) + " Peer " + connection.remoteAddress + " disconnected.");
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment