How Would I Build A NodeJS Websocket Server Without A Library

comet, javascript, json, node.js, websocket

Solution

Well, you'll basically just need to read the RFC and then implement it :)

At a high level WebSockets are not much more than an extended HTTP connection. They get initiated with an `UPGRADE` request alongside some handshaking. Afterwards the browser and server send `framed` messages over the existing HTTP TCP connection.

There are a few complications along the road though, as there are several versions of the WebSocket protocol out there and some of them don't support binary transport.

The RFC can be found here: https://www.rfc-editor.org/rfc/rfc6455

It's based on version 17 of the protocol. Which is, except, for some minor differences mostly Version 13.

There are still also some older Browsers around which only support the Version 6 of the protocol (where both framing and the initial handshake are quite different).

For a barebone implementation of version 6 and 13, you can check out a library of mine which pretty much does little more than to wrap the WebSocket protocol into the standard Node.js abstractions: https://github.com/BonsaiDen/lithium/tree/master/lib

Problem

I've recently built a small JSON webservice in NodeJS, and am interested in extending it to accept requests via WebSockets. Most of the WebSocket tutorials I have found so far are based on 3rd party modules like SocketIO. What does it take to write a WebSocket server? Assume that cross-browser compatibility is a non issue here, and that all my clients will have access to a decent browser.

Original source