Skip to content

Instantly share code, notes, and snippets.

@theturtle32
Created August 16, 2011 08:52
Show Gist options
  • Save theturtle32/1148686 to your computer and use it in GitHub Desktop.
Save theturtle32/1148686 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.");
});
}
@theturtle32
Copy link
Author

This is a modification of the server example from the WebSocket-Node README file. It bypasses the normal WebSocketServer class in favor of manually handling the node HTTP server's "upgrade" event, so that an older WebSocket library can be used as a fallback for older browsers.

@theturtle32
Copy link
Author

See the documentation for the WebSocketRequest constructor here: https://github.com/Worlize/WebSocket-Node/wiki/Documentation

@dvv
Copy link

dvv commented Aug 29, 2011

Hi! I read disclaimer about supporting only the latest draft, but wonder if you could provide some info on are there any drafts implementing /* some fallback code here */ ? What stub do you use at worlize.com, if any? Or what "standard" library can be used as fallback, what changes to make there to support new message structure?
TIA,
--Vladimir

@theturtle32
Copy link
Author

You can use node-websocket-server for draft-75 and draft-76 support: https://github.com/miksago/node-websocket-server

On worlize.com, we don't need a fallback because our client is written in Flash and uses my AS3WebSocket client library: https://github.com/Worlize/AS3WebSocket

@dvv
Copy link

dvv commented Sep 1, 2011

I see. I mostly wonder what interface should fallback server support so that the this and fallback servers share the same api, so that I don't repeat myself.

@theturtle32
Copy link
Author

theturtle32 commented Sep 1, 2011 via email

@dvv
Copy link

dvv commented Sep 1, 2011

Wonder if you could spend some time adopting previous drafts (that the docu states to reside in older branches) as a fallback? This done, we could have at least one robust WS server aware of all (or vast majority) currently available protocols.
Before I discovered WebSocket-Node I've been independently exploring the approach of having only native WebSocket + Flash shim in dvv/o4epegb . I'd like to have a barebone x-browser WebSocket with basic messaging (just like socket.io ago was). I feel to depend on WebSocket-Node would be the right choice.

@dvv
Copy link

dvv commented Sep 1, 2011

Also, would be great if you exampled the use of AS3WebSocket shim in a browser. How to load it? Do I need some JS to proxy Flash object? TIA, --Vladimir

@theturtle32
Copy link
Author

The library is still under development -- in particular, I'm planning on reworking it to provide a streaming API, and then build a message-oriented API on top of that (in a way that's backward compatible with applications already using the library). That's a fair amount of work, and I'd have to do it multiple times (one for each draft version) to support them all. I'd really rather not complicate the library with extra code that is there to support an obsolete draft version.

As for the AS3WebSocket library - it's an ActionScript 3 library distributed as a .swc file for importing into Flash Builder or use with the open source flex sdk. I haven't written a polyfill shim for javascript-based projects, my AS3WebSocket library is meant to be a client library for flash applications. It probably wouldn't be too hard to write a small flash application to expose the API to JavaScript, but I'm swamped with other work right now :-/

@nicokaiser
Copy link

Did anyone succeed in adding node-websocket-server to this example (to get a fallback for draft75/draft76 connections)?

@theturtle32
Copy link
Author

@nicokaiser I haven't had any reports from anyone.. :-/

@nicokaiser
Copy link

Unfortunately this does not work, "new WebSocketRequest" rejects older protocols (like draft-76) and closes the socket, so fallback libraries cannot do anything in the "catch" block.

@theturtle32
Copy link
Author

@nicokaiser -- As it turns out, you're quite right! Apologies! I've updated it the code in v0.0.16 not to automatically close the connection. That responsibility is deferred to WebSocketServer in the normal case, or you in the case where you're handling the fallback.

@theturtle32
Copy link
Author

I've updated the gist to reflect my update.

@nicokaiser
Copy link

Here is a Gist that implements a working example of a server that handles draft-08/-09/-10 connections with WebSocket-Node and the rest with miksago's node-websocket-server:

https://gist.github.com/1219165

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