Skip to main content

Real Time Chat With NodeJS, Socket.io and ExpressJS

Of course, the first thing to do is get NodeJS installed on your system. If you are a Windows or Mac user, you can visit nodejs.org and download the installer. If you instead prefer Linux, I'd suggest that you refer to this link. Although I won't go into further details on this, if you encounter any installation issues, I'm happy to help; just leave a comment below this post.
Once you have NodeJS installed, you're ready to setup the needed instruments.
  1. ExpressJS - this will manage the server and the response to the user
  2. Jade - template engine
  3. Socket.io - allows for real time communication between the front-end and back-end
Continuing on, within an empty directory, create a package.json file with the following content.
By using the console (under Windows - command prompt), navigate to your folder and execute:
Within a few seconds, you'll have all the necessary dependencies downloaded to the node_modulesdirectory.
Let's begin with a simple server, which will deliver the application's HTML page, and then continue with the more interesting bits: the real time communication. Create an index.js file with the following core expressjscode:
Above, we've created an application and defined its port. Next, we registered a route, which, in this case, is a simple GET request without any parameters. For now, the route's handler simply sends some text to the client. Finally, of course, at the bottom, we run the server. To initialize the application, from the console, execute:
The server is running, so you should be able to open http://127.0.0.1:3700/ and see:
Now, instead of "It works" we should serve HTML. Instead of pure HTML, it can be beneficial to use a template engine. Jade is an excellent choice, which has good integration with ExpressJS. This is what I typically use in my own projects. Create a directory, called tpl, and put the following page.jade file within it:
The Jade's syntax is not so complex, but, for a full guide, I suggest that you refer to jade-lang.com. In order to use Jade with ExpressJS, we require the following settings.
This code informs Express where your template files are, and which template engine to use. It all specifies the function that will process the template's code. Once everything is setup, we can use the .rendermethod of the response object, and simply send our Jade code to the user.
The output isn't special at this point; nothing more than a div element (the one with id content), which will be used as a holder for the chat messages and two controls (input field and button), which we will use to send the message.
Because we will use an external JavaScript file that will hold the front-end logic, we need to inform ExpressJS where to look for such resources. Create an empty directory, public, and add the following line before the call to the .listen method.
So far so good; we have a server that successfully responds to GET requests. Now, it's time to add Socket.io integration. Change this line:
to:
Above, we passed the ExpressJS server to Socket.io. In effect, our real time communication will still happen on the same port.
Moving forward, we need to write the code that will receive a message from the client, and send it to all the others. Every Socket.io application begins with a connection handler. We should have one:
The object, socket, which is passed to your handler, is actually the socket of the client. Think about it as a junction between your server and the user's browser. Upon a successful connection, we send a welcometype of message, and, of course, bind another handler that will be used as a receiver. As a result, the client should emit a message with the name, send, which we will catch. Following that, we simply forward the data sent by the user to all other sockets with io.sockets.emit.
With the code above, our back-end is ready to receive and send messages to the clients. Let's add some front-end code.
Create chat.js, and place it within the public directory of your application. Paste the following code:
Our logic is wrapped in a .onload handler just to ensure that all the markup and external JavaScript is fully loaded. In the next few lines, we create an array, which will store all the messages, a socket object, and few shortcuts to our DOM elements. Again, similar to the back-end, we bind a function, which will react to the socket's activity. In our case, this is an event, named message. When such an event occurs, we expect to receive an object, data, with the property, message. Add that message to our storage and update the content div. We've also included the logic for sending the message. It's quite simple, simply emitting a message with the name, send.
If you open http://localhost:3700, you will encounter some errors popup. That's because we need to update page.jade to contain the necessary JavaScript files.
Notice that Socket.io manages the delivery of socket.io.js. You don't have to worry about manually downloading this file.
We can again run our server with node index.js in the console and open http://localhost:3700. You should see the welcome message. Of course, if you send something, it should be shown in the content's div. If you want to be sure that it works, open a new tab (or, better, a new browser) and load the application. The great thing about Socket.io is that it works even if you stop the NodeJS server. The front-end will continue to work. Once the server is booted up again, your chat will be fine too.
In its current state, our chat is not perfect, and requires some improvements.
The first change that we need to make is to the identity of the messages. Currently, it's not clear which messages is sent by whom. The good thing is that we don't have to update our NodeJS code to achieve this. That's because the server simply forwards the data object. So, we need to add a new property there, and read it later. Before making corrections to chat.js, let's add a new input field, where the user may add his/her name. Within page.jade, change the controls div:
Next, in code.js:
To summarize the changes, we've:
  1. Added a new shortcut for the username's input field
  2. Updated the presentation of the messages a bit
  3. Appended a new username property to the object, which is sent to the server
If the the number of messages becomes too high, the user will need to scroll the div:
Keep in mind that the above solution will likely not work in IE7 and below, but that's okay: it's time for IE7 to fade away. However, if you want to ensure support, feel free to use jQuery:
It would also be nice if the input field is cleared after sending the message:
The final boring problem is the clicking of the send button each time. With a touch of jQuery, we can listen for when the user presses the Enter key.
The function, sendMessage, could be registered, like so:
Please note that this isn't a best practice, as it is registered as a global function. But, for our little test here, it'll be fine.
NodeJS is an extremely useful technology, and provides us with a great deal of power and joy, especially when considering the fact that we can write pure JavaScript. As you can see, with only a few lines of code, we managed to write a fully functional real time chat application. Pretty neat!

Comments

Popular posts from this blog

Socket.io

Socket.IO enables real-time bidirectional event-based communication. It works on every platform, browser or device, focusing equally on reliability and speed. Real-time analytics Push data to clients that gets represented as real-time counters, charts or logs. Binary streaming Starting in 1.0, it's possible to send any blob back and forth: image, audio, video. Instant messaging and chat Socket.IO's "Hello world" is a chat app in just a few lines of code. Document collaboration Allow users to concurrently edit a document and see each other's changes. USED BY EVERYONE From Microsoft Office, Yammer, Zendesk, Trello... to hackathon winners and little startups. One of the most powerful JavaScript frameworks on GitHub, and most depended-upon npm module. IMMENSELY POWERFUL, YET EASY TO USE Our getting started guide will show you how to create lots of amazing applications in fewer than 200 lines of code.

Angular

Angular (commonly referred to as "Angular 2+" or "Angular 2") is a TypeScript-based open-source front-end web application platform led by the Angular Team at Google and by a community of individuals and corporations to address all of the parts of the developer's workflow while building complex web applications. Angular is a complete rewrite from the same team that built AngularJS. Angular is a framework for building client applications in HTML and either JavaScript or a language like TypeScript that compiles to JavaScript. Angular combines declarative templates, dependency injection, end to end tooling, and integrated best practices to solve development challenges. Angular empowers developers to build applications that live on the web, mobile, or the desktop. DEVELOP ACROSS ALL PLATFORMS Learn one way to build applications with Angular and reuse your code and abilities to build apps for any deployment target. For web, mobile web, native mobile and native...

Angular Js

Why AngularJS? HTML is great for declaring static documents, but it falters when we try to use it for declaring dynamic views in web-applications. AngularJS lets you extend HTML vocabulary for your application. The resulting environment is extraordinarily expressive, readable, and quick to develop. Alternatives Other frameworks deal with HTML’s shortcomings by either abstracting away HTML, CSS, and/or JavaScript or by providing an imperative way for manipulating the DOM. Neither of these address the root problem that HTML was not designed for dynamic views. Extensibility AngularJS is a toolset for building the framework most suited to your application development. It is fully extensible and works well with other libraries. Every feature can be modified or replaced to suit your unique development workflow and feature needs. Read on to find out how. Data Binding Data-binding is an automatic way of updating the view whenever the model changes, as well as updating the mo...