The Talent500 Blog
websocket

Implementing a Real-time Chat Application using WebSockets and Socket.IO.

In today’s interconnected world, real-time communication has become a vital aspect of numerous applications. Whether it’s a collaborative workspace, a gaming platform, or a customer support system, the ability to exchange messages instantaneously enhances user engagement and productivity. To achieve such real-time communication, we can leverage the power of WebSockets and Socket.IO. In this tutorial, we will explore the process of implementing a real-time chat application using these technologies.

What are WebSockets and Socket.IO? 

WebSockets is a communication protocol that provides full-duplex communication channels over a single TCP connection. Unlike traditional HTTP requests, which are unidirectional, WebSockets enable bidirectional, real-time communication between clients and servers. It allows the server to push data to clients and vice versa, creating a truly interactive experience.

Socket.IO is a JavaScript library built on top of WebSockets that simplifies the implementation of real-time applications. It abstracts away the complexities of handling low-level WebSocket operations and provides a high-level API that developers can use to build real-time applications effortlessly.

Prerequisites

Before we dive into the implementation, let’s make sure we have the following prerequisites in place.

A basic understanding of HTML, CSS, and JavaScript.

Node.js and npm (Node Package Manager) installed on your machine.

Setting up the Project

Implementing a Real-time Chat Application using WebSockets and Socket.IO. 1

To get started, we need to set up a new Node.js project and install the required dependencies. Open your terminal and follow the steps below

Step 1: Create a new directory for your project:

bash

Copy code

mkdir chat-app

cd chat-app

Step 2: Initialize a new Node.js project:

csharp

Copy code

npm init -y

Step 3: Install Express and Socket.IO:

lua

npm install express socket.io

Implementing the Server 

Implementing a Real-time Chat Application using WebSockets and Socket.IO. 2

Now that our project is set up, let’s start by implementing the server-side of our chat application. Create a new file called server.js and add the following code.

javascript

// Import dependencies

const express = require(‘express’);

const app = express();

const http = require(‘http’).createServer(app);

const io = require(‘socket.io’)(http);

 

// Serve static files

app.use(express.static(‘public’));

 

// Handle WebSocket connections

io.on(‘connection’, (socket) => {

  console.log(‘A user connected’);

 

  // Handle incoming chat messages

  socket.on(‘chat message’, (msg) => {

    console.log(‘Received message:’, msg);

    // Broadcast the message to all connected clients

    io.emit(‘chat message’, msg);

  });

 

  // Handle disconnections

  socket.on(‘disconnect’, () => {

    console.log(‘A user disconnected’);

  });

});

 

// Start the server

const PORT = 3000;

http.listen(PORT, () => {

  console.log(`Server listening on port ${PORT}`);

});

In the above code, we first import the required dependencies: Express, Socket.IO, and the built-in http module. We then create an Express application, create an HTTP server using the http module, and initialize Socket.IO by passing the HTTP server instance.

Next, we serve static files from a public directory using Express’s express.static middleware. This allows us to serve our client-side files, such as HTML, CSS, and JavaScript.

We handle WebSocket connections using the io.on(‘connection’) event, which is triggered whenever a client establishes a WebSocket connection with the server. Inside this event handler, we listen for the ‘chat message’ event, which is emitted by clients when they send a chat message. 

We log the received message and broadcast it to all connected clients using io.emit(‘chat message’). Additionally, we handle the ‘disconnect’ event to log when a user disconnects from the chat.

Finally, we start the server on port 3000 and log a message to indicate that the server is running.

Implementing the Client 

Implementing a Real-time Chat Application using WebSockets and Socket.IO. 3

Now let’s implement the client-side of our chat application. Create a new directory called public and inside it, create three files: index.html, style.css, and script.js. Add the following code to each file.

index.html

html

Copy code

<!DOCTYPE html>

<html>

<head>

  <title>Real-time Chat Application</title>

  <link rel=”stylesheet” type=”text/css” href=”style.css”>

</head>

<body>

  <ul id=”messages”></ul>

  <form id=”chat-form”>

    <input id=”message-input” autocomplete=”off” />

    <button type=”submit”>Send</button>

  </form>

 

  <script src=”/socket.io/socket.io.js”></script>

  <script src=”script.js”></script>

</body>

</html>

style.css:

 

css

 

body {

  font-family: Arial, sans-serif;

  margin: 0;

  padding: 20px;

}

 

form {

  display: flex;

  margin-top: 20px;

}

 

input[type=”text”] {

  flex: 1;

  padding: 10px;

}

 

button {

  padding: 10px 20px;

  background-color: #007bff;

  color: #fff;

  border: none;

  cursor: pointer;

}

script.js:

 

javascript

 

const socket = io();

 

// Handle form submission

document.getElementById(‘chat-form’).addEventListener(‘submit’, (e) => {

  e.preventDefault();

  const messageInput = document.getElementById(‘message-input’);

  const message = messageInput.value.trim();

  if (message !== ”) {

    socket.emit(‘chat message’, message);

    messageInput.value = ”;

  }

});

 

// Handle incoming chat messages

socket.on(‘chat message’, (msg) => {

  const messages = document.getElementById(‘messages’);

  const li = document.createElement(‘li’);

  li.textContent = msg;

  messages.appendChild(li);

  messages.scrollTop = messages.scrollHeight;

});

In the client-side code, we first include the Socket.IO library by adding <script src=”/socket.io/socket.io.js”></script> to our HTML file. This script tag allows the client to connect to the Socket.IO server.

In the JavaScript code, we create a socket instance by calling io(), which establishes a WebSocket connection with the server. We then listen for the form submission event and emit a ‘chat message’ event to the server when the user sends a message. 

We also handle incoming chat messages by appending them to the message list and scrolling to the bottom of the list to ensure the latest messages are visible.

Conclusion

In this article, we explored the process of implementing a real-time chat application using WebSockets and Socket.IO. We started by setting up a Node.js project and installing the necessary dependencies. Then, we implemented the server-side using Express and Socket.IO, handling WebSocket connections and managing chat messages. Finally, we created the client-side files and established a WebSocket connection with the server using Socket.IO. The result is a fully functional real-time chat application that allows users to exchange messages instantly.

WebSockets and Socket.IO provide a powerful combination for building real-time applications, enabling developers to create interactive and engaging user experiences. By leveraging these technologies, you can take your applications to the next level and provide users with seamless real-time communication capabilities.

Remember to explore further and experiment with additional features, such as user authentication, private messaging, or even integrating chatbots. The possibilities are endless, and with the foundation laid out in this tutorial, you’re well-equipped to take on more complex real-time projects. 

 

0
Shubham Singh

Shubham Singh

He is a SDE-2 DevOps Engineer, with demonstrated history in working with scaling startup. A problem solver by mettle, who loves watching anime when he is not working. He is a learner and educator by heart.

Add comment