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 patibility is a non issue here, and that all my clients will have access to a decent browser.
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 patibility is a non issue here, and that all my clients will have access to a decent browser.
Share Improve this question edited May 29, 2014 at 12:59 Charlie asked May 29, 2014 at 12:41 CharlieCharlie 4,3296 gold badges45 silver badges60 bronze badges 4- From glancing at the WebSockets spec (tools.ietf/html/rfc6455) this might be a large task. You could probably also take an existing library and modify it. – Hector Correa Commented May 29, 2014 at 12:53
- 3 SocketIO is not a WebSocket library; its at a higher level than that. You may want to look at ws, which abstracts away the protocol without trying to add more protocol like SocketIO does. – Aaron Dufour Commented May 29, 2014 at 13:55
- @Aaron - Can deny that I appeciate the suggestion to look at WS, but I am quite interested in learning about what it would take to write a WebSocket server from scratch. – Charlie Commented May 29, 2014 at 15:57
- Where 'Can' == 'Can't'. – Charlie Commented May 29, 2014 at 16:07
2 Answers
Reset to default 5Well, 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 plications 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/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./BonsaiDen/lithium/tree/master/lib
I would begin by looking over the source for this project: https://github./Worlize/WebSocket-Node