Jeff Kreeftmeijer

Node.js, web sockets and talking mice

2010-08-09
If you see extra mouse cursors moving around: don’t worry, they’re part of the demo. You can always disable them if you want.

Since my first two articles about my Node.js experiment were a great success, got a lot of reponses and even inspired some people to get their hands dirty, I decided to dive into the demo code once more and write a very last article about it.

If you have no idea what this is all about, please start by reading “Experimenting with Node.js” and “Things I learned from my Node.js experiment”.

This time, I’ve added the ability to chat with other cursors — with Gravatar support! — you can try it out by putting your e-mail address in the left input, your message in the right and hitting enter.

I’m only using your e-mail address to fetch your Gravatar. I’m not saving anything.

When you submit the form, it sends your e-mail address and message to the web socket server. After your e-mail address is encrypted to MD5 with Node’s crypto module, it gets broadcasted to the other clients together with your message:

if(request.action == 'speak') {
  request.email = crypto.createHash('md5').
                  update(request.email).digest("hex");
  client.send(json(request));
}

request.id = client.sessionId
client.broadcast(json(request));

The encrypted e-mail address and message also get sent back to the client it came from, to be able to show users their own messages after sending them out.

When the message gets received on the client side, a bit of jQuery makes sure the Gravatar and the message get displayed:

function speak(data){
  clearTimeout(timeouts[data['id']]);
  $('#mouse_'+data['id']+' img').remove();
  $('#mouse_'+data['id']).append('<img src="http://www.gravatar.com/avatar/' + data['email'] + '?s=20" />');
    
  if(data['text'] == '') {    
    return $('#mouse_'+data['id']+' .chat').hide();
  }
  
  $('#mouse_'+data['id']+' .chat').show().html(data['text']);   
  timeouts[data['id']] = setTimeout("$('#mouse_"+data['id']+" .chat').hide()", 5000)
};

Also, a timeout gets created that removes the message from the screen after five seconds to try to keep your screen from overflowing.

Like before, the Gist with all the code I wrote for the experiment is updated in case you want to use it to build something awesome. If you do, please let me know. I’d love to see what you come up with and I might even write another very last article.

That wraps up my Node.js-web-socket-mouse-cursor-experiment, thanks again for the responses everyone. You certainly helped me out a lot trying to build this thing. As you might have guessed, I’m seriously excited about Node.js and there will probably be more experiments and articles like this.

Stay tuned and please let me know how you liked the experiment in the comments.