a touch of madness
I recently led a second tech talk at my job, and to adequately explain websockets, I built perhaps the dumbest project yet:
ClickClique is a competitive real-time button-masher wherein you and your friends trigger that mousedown event as fast as you can. On the front-end, visiting the site establishes a two-way websocket connection with the nodeJS server:
When you click, the x and y coordinates are sent using the built-in .send() method:
The server stores everybody's connection in local memory, in an object, meaning no database is necessary:
Instead, there’s a big ol’ array of “clicks” - (x,y) coordinate pairs with timestamps and randomly generated user IDs. Incidentally, those user IDs are constructed such that they can be used as hexadecimal color values:
When you add a new click to the clicks array, the oldest one is pushed out - so there are never more than 100:
Then this updated array is sent out, and not just to the clicker, but to everyone:
In a long-polling or short-polling AJAX application, this would be either more resource-intensive or less immediate, respectively. But websockets make it seamless. Anyway, the background color updates to show who's winning, and a small CSS transition depicts the opponent clicks as growing, fading circles:
When I showed this to a room full of software engineers, of course someone wrote a script that auto-clicked 100 times a second... but outside of cheating, can you best your friends?
tl;dr: websocket is great for instantaneous two-way communication; click listeners give you the event position with .clientX and .clientY; CSS transitions are a simple way to gradually adjust height, width, and opacity
project: ClickClique











