computer keyboard

NowJS and Node.js Tutorial – Creating a multi room chat client

Node.js is a server side environment for Javascript. NowJS is a framework built on top of Node.js that connects the client side and server side Javascript effortlessly.

The core of NowJS functionality lies in the now object.The now object is special because it exists on the server and the client.

This means variables you set in the now object are automatically synced between client and server. Also server functions can be directly called on the client and client functions can be called directly from the server.

All in realtime.

You can have a working HTTP server up and running in Node.JS with just a few lines of code. For example -

  1. var http = require('http');
  2. http.createServer(function (req, res) {
  3.     res.writeHead(200, {'Content-Type': 'text/plain'});
  4.     res.end('Hello World\n');
  5. }).listen(8080);

This little snippet of code will create an HTTP server, listen on port 8080, and send back “Hello World” for every request. That’s it. Nothing more needed.

Using NowJS, communication between the client and server side is just as simple.

Client Side:

  1. <script type="text/javascript">
  2. now.ready(function(){
  3.     now.clientSideVariable = 'someValue';
  4.     now.serverSideFunction();
  5. });
  6. </script>

In this code snippet, the client side sets a variable to ‘someValue’ and calls serverSideFunction(), which is declared only on the server.

Server Side:

  1. everyone.now.serverSideFunction = function() {
  2.     console.log(this.now.clientSideVariable);
  3. }

The server side is then able to access clientSideVariable, which is declared only on the client.

All the details such as establishing connections and communicating change of data between the server and client are handed automagically by the framework.

In fact writing code using this framework is so simple, the NowJS hello world example is a working chat client and server written in under a dozen lines of code. Go check it out.

As a simple exercise to get comfortable with the NowJS API, we can modify the chat client example to support multiple chat rooms. Let’s take a look at how easy it is.

Server Side (multiroom_server.js)

1. The first thing we need to do is modify the distributeMessage() function to only send messages to users in the same chat room as the user.

  1. // Send message to everyone in the users group
  2. everyone.now.distributeMessage = function(message){
  3.     var group = nowjs.getGroup(this.now.serverRoom);
  4.     group.now.receiveMessage(this.now.name+'@'+this.now.serverRoom, message);
  5. };

We store the name of the server room on the client side (this.now.serverRoom). When the client calls the distributeMessage() function we send the message to everyone in the same chat room by using getGroup() and using the group.now object instead of the everyone.now object. (everyone is just a group that contains all users connected to the server)

2. Next we need to handle the client changing chat rooms.

  1. everyone.now.changeRoom = function(newRoom){
  2.     var oldRoom = this.now.serverRoom;
  3.  
  4.     //if old room is not null; then leave the old room
  5.     if(oldRoom){
  6.         var oldGroup = nowjs.getGroup(oldRoom);
  7.         oldGroup.removeUser(this.user.clientId);
  8.     }
  9.  
  10.     // join the new room
  11.     var newGroup = nowjs.getGroup(newRoom);
  12.     newGroup.addUser(this.user.clientId);
  13.  
  14.     // update the client's serverRoom variable
  15.     this.now.serverRoom = newRoom;
  16. };

The getGroup() method fetches the group object if it exists and creates a group if it doesn’t already exist. We use the groups addUser() and removeUser() methods to move the client from the old room to the new room.

Thats about it on the server side.

Client Side (multiroom.html)

3. First we add a drop down with the list of server rooms.

  1. <select>
  2.     <option selected="selected" value="room1">Room 1</option>
  3.     <option value="room2">Room 2</option>
  4.     <option value="room3">Room 3</option>
  5. </select>

4. Next we call the server side changeRoom() function when the user first connects and whenever the drop down is changed.

  1. // on establishing 'now' connection, set the server room
  2. now.ready(function(){
  3.     // By default pick the first chatroom
  4.     now.changeRoom($('#server-room').val());
  5. });
  6.  
  7. // On change of drop down, clear text and change server room
  8. $('#server-room').change(function(){
  9.     $("#messages").html(");
  10.     now.changeRoom($('#server-room').val());
  11. });

5. For extra credit, we can allow the server to dynamically provide the list of rooms when the client connects.

The changes required would be -

Server Side:

  1. // Declare a list of server rooms
  2. everyone.now.serverRoomsList = {'room1':'Room 1','room2':'Room 2','room3':'Room 3'};

Client Side:
  1. now.ready(function(){
  2.     // Pick up list of chatrooms from server and populate dropdown
  3.     setServerRoomFromList(now.serverRoomsList);
  4.     // By default pick the first chatroom
  5.     now.changeRoom($('#server-room').val());
  6. });
  7.  
  8. // populate the #server-room dropdown from a list
  9. function setServerRoomFromList(roomList){
  10.     $('#server-room').empty();
  11.     $.each(roomList, function(key, value){
  12.         $('#server-room').
  13.         append($("").
  14.         attr("value",key).
  15.         text(value));
  16.     });
  17. }

That’s really all you need to do. We now have a multi room chat client/server with
i) A drop down on the client side with list of server rooms
ii) On connection with server, client auto populates server room list and enters the first room
iii) Changing drop down changes room
iv) Entering new room clears the screen for the user

This is obviously a fairly barebones version (like the original example), but it serves as a proof of concept of all the essential elements of NowJS communication.

The finished code has some extra comments and a few more features. You can download the complete source code below.

Leave a Reply