7

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.

Charlie
  • 4,197
  • 5
  • 42
  • 59
  • From glancing at the WebSockets spec (http://tools.ietf.org/html/rfc6455) this might be a large task. You could probably also take an existing library and modify it. – Hector Correa May 29 '14 at 12:53
  • 3
    SocketIO is not a WebSocket library; its at a higher level than that. You may want to look at [ws](https://github.com/einaros/ws), which abstracts away the protocol without trying to add more protocol like SocketIO does. – Aaron Dufour May 29 '14 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 May 29 '14 at 15:57
  • Where 'Can' == 'Can't'. – Charlie May 29 '14 at 16:07

2 Answers2

5

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

Community
  • 1
  • 1
Ivo Wetzel
  • 46,459
  • 16
  • 98
  • 112
0

I would begin by looking over the source for this project: https://github.com/Worlize/WebSocket-Node

Michael Benin
  • 4,317
  • 2
  • 23
  • 15