A chatroom for all! Part 5 - Connecting the Chatroom with WebSockets

Thisnode.jstutorial series will help you build a node.js powered real-time chatroom web app fully deployed in the cloud. You are expected to know HTML5 and JavaScript. Throughout the series, you will learn how to setup node.js on your Windows machine, how to develop a web frontend withexpress , how to deploy a node express apps toAzure , how to usesocketioto add a real-time layer and how to deploy it all together.

Level: Beginner to Intermediate.

Part 1 - Introduction to Node.js

Part 2 - Welcome to Express with Node.js and Azure

Part 3 - Building a Backend with Node, Mongo and Socket.IO

Part 4 – Building a Chatroom UI with Bootstrap

Part 5 - Connecting the Chatroom with WebSockets

Part 6 – The Finale and Debugging Remote Node Apps

Part 5 – Connecting the Chatroom with WebSockets

Welcome to Part 5 of Node.js Tutorial Series: A chatroom for all! In this part, I will show you how to connect your front-end chatroom to the node chatroom backend which we have built in Part 2, Part 3 and Part 4.

Adding jQuery, SocketIO and index.js

The first thing we want to do before we start writing our frontend JavaScript code is to ensure the files and dependencies we need are going to be delivered by the node server. Let’s add jQuery and socket.io first to the layout.jade file which is extended by all the other jade files in our project.

What I want to do is replace the single link to bootstrap.min.js with a link to all the other files we need.

 script(type='text/javascript' src='http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.1.min.js')
script(type='text/javascript' src='/js/bootstrap.min.js')
script(type='text/javascript' src='/socket.io/socket.io.js')

Note, the first line link to jQuery hosted on the Microsoft Ajax Content Delivery Network. This CDN hosts popular third party JavaScript libraries such as jQuery and enables you to easily add them to your Web applications. You can significantly improve the performance of your Ajax applications by using a CDN. The contents of the CDN are cached on servers located around the world. The CDN supports SSL (HTTPS) in case you need to serve a web page using the Secure Sockets Layer.

Now I will add one more line at the end to create a new block.

 block body_end

I am doing this so that any Jade file that extends layout.jade can also add script tags right before the end of the body tag.

Now we want to use that new block to add a link to our index.js file which we will create in the public/js folder, make sure to create the file.

 block body_end
  script(type='text/javascript' src='/js/index.js')

Make sure that the block starts with zero indentation to follow Jade coding conventions. If you run the node server and navigate to the main page in your browser, you will notice in your F12 tools that the files are being served correctly.

Quick Changes to app.js

Now there’s a few things I want to change in app.js. First, I want to reverse the sorting direction so that the oldest messages are sent first and second, I want to emit the previously received chat messages on the same channel as I plan on receiving the new messages. The changes will go to line 49 and 50 in app.js. This is the result:

 var stream = collection.find().sort().limit(10).stream();
stream.on('data', function (chat) { socket.emit('chat', chat.content); });

Don’t forget to set the CUSTOMCONNSTR_MONGOLAB_URI environment variable before rerunning the app.js file as otherwise the node backend will crash when it can’t connect to your MongoDB.

Powering Up the Send Button

It is time to power up that send button to send messages in the message box using WebSockets to the backend server on the chat channel.

  1 2 3 4 5 6 7 8 91011
 var socket = io();$('#send-message-btn').click(function () {    var msg = $('#message-box').val();    socket.emit('chat', msg);    $('#messages').append($('<p>').text(msg));    $('#message-box').val('');    return false;});socket.on('chat', function (msg) {    $('#messages').append($('<p>').text(msg));});

Line 1

We want to create a socket and we can do that by calling the io() function which is in the socket.io-client.js file.

Line 2

Followed by that, we want to execute a function on the click of the send message button using the jQuery’s $ function and the click event handler.

Line 3

We will get the string value in the message box using jQuery’s $ function.

Line 4

This is where the interesting thing happens, we use the emit function on the socket variable we created in line 1 to send a message on the ‘chat’ channel containing the message box’s value.

Line 5-7

At this point, we will append the message in the message box to the #messages div so that the user can see the message was sent. We will assign the value of the message box to an empty string to clear it up.

Line 9-10

Now we want to make sure to append the message received on the chat channel from other users to the #messages div. The node backend will not resend the message that the client wrote back to itself but that’s alright because we added the message right away in the click function handler.



Voila, this article shows you how to connect your backend and your frontend using WebSockets. If you want to identify the people in the chatroom or add an avatar for each user, it is up to you but you can use this chatroom onward. In next week’s part, I will show you how to deploy this anonymous chatroom to Azure and show you how you can debug it.

Stay tuned for Part 6! You can stay up to date by following my twitter account @ramisayar.