Spark Doodle: <canvas> and websockets

The source code for this post is on github here. You can play with the app on Heroku here. This app was based on David Ase’s chat tutorial and on Code and Coffee’s node.js example.

Websockets allow duplex communication over a single TCP connection – in other words, they let the web browser constantly speak and listen to a server instead of doing everything through atomized HTTP requests. Before websockets, if you wanted (for instance) a chat app in the web browser, you’d use polling to constantly ask the server whether anything changed. Websockets allow the server to push information to the browser without waiting to be asked.

In this post, I’ll show you how to use websockets to build a simple shared doodling app. Users will see all the lines that other users draw while they are logged in, but they won’t see lines that were drawn before they arrived, nor will they see their own lines reappear if they close and re-open the browser window. The server will use Spark, and the client will be pure, no-library-having Javascript.

The main() method of a Spark application traditionally sets up the routes, but here, all our requests go to the index.html page in /src/main/resources/public, as indicated by the staticFileLocation() call. The webSocket() call sets up the websocket, running at “/doodle” and handling responses using the DoodleWebSocket class. Finally, I put the list of sessions and the broadcastMessage() methods inside this Application class.

Our websocket handler implementation is spartan indeed! Spark uses Jetty’s websocket implementation directly, including Jetty’s annotations. All we do here is add and remove sessions and call the Application controller to broadcast our message out to the clients.

That’s all the java code for this application!

We need some HTML to give ourselves a canvas to draw on:

We have a <canvas> and we include the js source.

Finally, the javascript:

The conceptual implementation is directly from Code and Coffee’s post: if the mouse has moved in the past 25 milliseconds and the mouse button is clicked, we broadcast the instruction to draw a line between our mouse pointer’s current position and the previous position.

The meat of my change is:

  • Switch from a socket.io socket to a plain vanilla websocket
  • add the line to re-create the websocket when the mouse is clicked
  • add the proxy function to wait for the socket to be ready before sending a message.

Re-creating the websocket on mouse clicks is to resolve an issue where the websockets would time out on heroku. The proxy function is there because otherwise we’d be trying to broadcast messages to a socket that wasn’t open yet.

One thought on “Spark Doodle: <canvas> and websockets

  1. Pingback: Touch Events: Doodling from Mobile Browsers | Kaiser Leib

Comments are closed.