Recently at Viaro Networks, I created the chat functionality for a product of one of our clients. Based on this experience, I believe the best way to add this functionality is by using WebSockets. Although our client requested a bigger implementation, for the purpose of this post, I’ll explain how you can do a basic implementation. I will just focus on how to send and receive messages from a lot of clients.
What is WebSocket?
The WebSocket API is a technology that provides a two-way interactive communication session between the user’s browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply (you can check the API here).
WebSocket is a computer communications protocol, it provides a full-duplex communication channel over a single TCP connection. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011, and the WebSocket API in Web IDL is being standardized by the W3C (to learn further about Websoket visit this link)
To sum up, we use WebSockets to send messages from the client to the server. For this tutorial, we will focus on using WebSockets to broadcast a message to the client connections.
Implement NodeJs WebSocket
There are a lot of articles regarding this on the internet, however, I prefer to show you a simple example that I implemented in my local environment.
1. We need to install the library using the command “npm install WebSocket”. After the installation, the package.json file should look like this:
2. Create a WebSocket server using node.js
Connect the UI with NodeJs WebSocket
To connect the UI with NodeJs WebSocket, I created a little chat application using HTML, CSS, and jQuery. You can check step by step the code I implemented for this example:
1. For this example, this is a basic UI you can use:
2. This is the Html file I created:
3. And this is the code I used for the WebSocket client:
Finally, to show you how it works I opened two instances of the index.html to allow chatting with two clients. You can see below how the messages arrive on each session.
In short, I kept this example very basic to demonstrate how to create a simple chat using Websockets. In a real environment, we must identify each client that will be connected to the socket with an identifier and possibly their IP address. Additionally, I would recommend improvement to the user interface, adding a database to save chat history, among other features.
While working on this project, I learned about WebSockets and my next step is to learn about AWS web sockets.
I encourage you to use WebSockets for many solutions, it is very helpful to learn more about it.