Rami Sayar May 11th, 2015

Hands-On: Build a Node.js-powered Chatroom Web App (Part Five)

This Node.js tutorial series will help you build a Node.js powered real-time chatroom web app fully deployed in the cloud. Throughout the series, you will learn how to setup Node.js on your Windows machine, how to develop a web frontend with Express, how to deploy a Node Express-based app to Microsoft Azure, how to use Socket.IO to add a real-time layer, and how to deploy it all together. Level: Beginner to Intermediate--you are expected to know HTML5 and JavaScript

Part 5 – Connecting the Chatroom with WebSockets

Welcome to Part 5 of the hands-on Node.js tutorial series: Build a Node.js-powered chatroom web app. In this installment, I will show you how to connect the front-end chatroom to the node chatroom backend that you 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. 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 links 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

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 also 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.
var socket = io();
$('#send-message-btn').click(function () {
    var msg = $('#message-box').val();
    socket.emit('chat', msg);
    $('#messages').append($('
').text(msg)); $('#message-box').val(''); return false; }); socket.on('chat', function (msg) { $('#messages').append($(' ').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 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 We want 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. Welcome

Conclusion

Voila! You have connected 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 the next installment, 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! Part 6— The Finale and Debugging Remote Node Apps!—will be posted to Noupe soon, and is also located on my blog here. You can stay up-to-date on this and other articles by following my twitter account: @ramisayar.

More Parts of the Series on MSDN

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

More Learning for node on Azure

For more in-depth learning on node, my course is available here on Microsoft Virtual Academy. Or some shorter-format videos on similar node subjects: This article is part of the web dev tech series from Microsoft. We’re excited to share Microsoft Edge and its new rendering engine with you. Get free virtual machines or test remotely on your Mac, iOS, Android, or Windows device @ modern.IE. Image by Gerd Altmann from Pixabay  (dpe)

Rami Sayar

Rami Sayar is a technical evangelist at Microsoft Canada focusing on web development (JavaScript, AngularJS, Node.js, HTML5, CSS3, D3.js, Backbone.js, Babylon.js), open data and open source technologies (Python, PHP, Java, Android, Linux, etc.) Read his blog or follow him @ramisayar on Twitter.

Leave a Reply

Your email address will not be published. Required fields are marked *