d3.js scene controlled by remote data using node.js and socket.io

d3.js is cool. So is node.js. Hence, doing something with both technologies is almost a logical consequence.

Start the Demo at least in two browser instances/devices (tested with Firefox, Chrome, IE9+, iPad, iPhone). Then click to create and to burst bubbles. Drag the bubbles around and try the action buttons to force larger changes to the d3.js scene.

This demo maintains a pool of “circles” on the server and implements the distributed MVC pattern. The Model is kept on the server. Each instance of the browser keeps a copy of the View and the Controller. Furthermore, a lightweight version of the model is used for data presentation and is processed by the d3 engine. The node.js based server is responsible for synchronization of all models via push messages. All user interaction triggers a change on the server model first. This holds true even for the initiating client. An example scenario follows:

  1. user clicks on a bubble
  2. the event handler reads the „id“ of the SVG-circle element and calls the server side function remove(id)
  3. the server updates the model
  4. the server calls the removeData(id) function for each connected client (including the initiating one)
  5. the data structure in the client is updated (in this example the object with the specified id is removed)
  6. d3.js scene is updated

The static files (index.html, CSS, templates and Javascript files) are served using express.js. The socket.io library is used as a convenience layer on top of websockets and provides a reliable permanent server/client connection.

Remarks regarding performance issues:

  • the good news: node.js and websockets are blazingly fast, playing with the demo for some minutes in three browser instances generates a CPU usage time for the node.js process of about 5 seconds, i.e. there is plenty of room for more serious stuff
  • advice: use SVG opacity styles instead of HTML opacity styles whenever possible, this reduces the SVG render time and enables larger SVG scenes (10 fold improvement in Firefox)

The source code for the server application is as follows:

The server model:

The client code:

complete source code as tar file

Schreib einen Kommentar