Building Interactive Web Applications with WebSockets and Socket.IO

With the continuous development and advancement of the web, a high standard of user experiences is expected. One of the crucial aspects of a great experience is real-time communication between server and client-side. WebSockets and the popular library, Socket.IO, come to the rescue for these real-time and low latency use cases.

In this tutorial, we will learn about the WebSocket protocol and how it works. We will then build a simple interactive web application using Node.js, Express, and Socket.IO.

What are WebSockets?

WebSocket is a communication protocol designed for bidirectional and full-duplex communication between a server and a client over a persistent connection. Typical web communication happens over HTTP protocol where the client sends a request to the server, and the server responds. With WebSocket, the server can also initiate communication with the client without waiting for the client's request, providing real-time updates and interactions.

WebSocket connections are established through a process called a WebSocket handshake. The handshake is done over HTTP protocol, and once the connection is established, the communication switches to WebSocket protocol.

Socket.IO

Socket.IO is a library built on top of the WebSocket protocol, which makes it easier for developers to work with WebSockets. The library offers features such as auto-reconnecting, broadcasting, namespaces, and more. Socket.IO is platform-independent, and the server-side library is compatible with Node.js while the client-side library is compatible with all modern browsers.

Let's Build an Interactive Web Application

For this tutorial, we will build a simple real-time chat application using Node.js, Express, and Socket.IO. The chat application will allow multiple users to open the web page, enter their username, and send messages to the chatroom. Each message is broadcasted to all connected users in real-time, providing a great interactive experience.

Prerequisites

Before we start, make sure you have Node.js installed on your computer. Knowledge of basic Node.js, Express, JavaScript, and HTML/CSS is recommended but not mandatory.

Create a new Node.js project

Start by creating a new directory for our chat app and initializing a new Node.js project:

mkdir websocket-chat-cd websocket-chat-npm init -y

This will create a new package.json file. Next, we will install the required dependencies:

npm install express socket.io

Setting up our Express server

Create a new file called server.js in the project directory and add the following code:

const express = require('express');const app = express();const http = require('http');const server = http.createServer(app);const { Server } = require('socket.io');const io = new Server(server);const PORT = process.env.PORT || 3000;app.use(express.static(__dirname + '/public'));server.listen(PORT, () => {console.log(`Server listening on port ${PORT}`);});

The code above sets up an Express server to serve the static assets from /public directory, and it creates a new Socket.IO server that listens for the WebSocket connections.

Creating the HTML structure

Create a new directory called public and inside it create a new file called index.html with the following content:

<!DOCTYPE html><html lang='en'><head>  <meta charset='UTF-8'>  <meta name='viewport' content='width=device-width, initial-scale=1.0'>  <title>WebSocket Chat</title>  <link rel='stylesheet' href='styles.css'></head><body>  <div class='container'>    <h1>WebSocket Chat</h1>    <p>Enter your username:</p>    <input type='text' id='username'>    <button id='submit'>Submit</button>    <div id='chat'>      <div id='messages'></div>      <input type='text' id='message'>      <button id='send'>Send</button>    </div>  </div>  <script src='/socket.io/socket.io.js'></script>  <script src='script.js'></script></body></html>

This creates the basic structure of our chat app. The user will first need to enter their username before they can start chatting. Add some basic CSS for styling in a new file called styles.css.

The client-side JavaScript

Create a new file called script.js inside the public directory and add the following code:

document.addEventListener('DOMContentLoaded', () => {const socket=io();let username;document.querySelector('#submit').addEventListener('click', () => {username=document.querySelector('#username').value.trim();if(username){document.querySelector('#chat').style.display='block';document.querySelector('#username').disabled=true;document.querySelector('#submit').disabled=true;}});document.querySelector('#send').addEventListener('click', () => {const message=document.querySelector('#message').value.trim();if(message){socket.emit('sendMessage', {username, message});}});socket.on('receiveMessage', data => {const div=document.createElement('div');div.innerHTML=`${data.username}: ${data.message}`;document.querySelector('#messages').appendChild(div);});});

This code handles the user interactions and sends the message to the server using the sendMessage event through Socket.IO. It also sets up an event listener for the message received from the server using the socket.on('receiveMessage', ...).

Handling the message on the server

Now, let's handle the message on the server-side. Go back to your server.js file and add the following:

io.on('connection', socket => {socket.on('sendMessage', data => {io.emit('receiveMessage', data);});});

This code listens for the incoming sendMessage event and broadcasts the message to all connected clients using the receiveMessage event.

Testing the application

Now your application is complete. To test it, run the following command:

node server.js

Open the browser and visit localhost:3000. Test the chat application with multiple browser windows.

Conclusion

In this tutorial, you've learned about the WebSocket protocol, Socket.IO library, and built an interactive chat application using WebSockets, Socket.IO, Node.js, and Express. You can further extend this application to add more features or build different applications such as real-time dashboards, gaming, and more.