Notifications 0

CodeGoundAI

ReadsNew

Speed TestNew

Code Grounds

RustGo LangNode JSPython 3C++JavaWeb(HTML, CSS, JS)

Data Grounds

RedisMongoDBPostgres

Tools New

Epoch ConverterCanvas Drawing boardBase64 EncodeBase64 DecodeJSON Web TokensJSON Diff

Popular

ReadsGrounds

Features

Realtime SharingShared OwnershipFast CompilationCloud Storage

Contact us

[email protected]

More to Explore

Sitemap

We @ CodeGroundAI

About UsPrivacy Policy

How to Build a Real-Time Chat Application with Node.js and WebSocket

Shubham Mehta - April 4, 2025


Real-time chat applications are an essential feature of modern web applications, allowing users to communicate instantly. In this tutorial, we will walk you through the process of building a simple real-time chat application using Node.js and WebSocket. By the end of this guide, you will have a functional chat application that you can customize and expand upon.


Prerequisites

Before we start, make sure you have the following installed on your machine:

  1. Node.js (v14 or later)
  2. npm (comes with Node.js)
  3. A text editor (e.g., VS Code)


Step 1: Set Up Your Project

A. Create a new directory for your project:

mkdir real-time-chat
cd real-time-chat

B. Initialize a new Node.js project:

npm init -y

C. Install the necessary packages:

npm install express ws


Step 2: Create the Server

First, we'll set up a simple server using Express and WebSocket.

  1. Create a file named server.js:
touch server.js
  1. Add the following code to server.js:
const express = require('express');
const http = require('http');
const WebSocket = require('ws');

const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

// Serve the static files
app.use(express.static('public'));

// WebSocket connection
wss.on('connection', (ws) => {
console.log('New client connected');

ws.on('message', (message) => {
console.log(`Received: ${message}`);
// Broadcast the message to all clients
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});

ws.on('close', () => {
console.log('Client disconnected');
});
});

// Start the server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});


Step 3: Create the Client

Next, we'll create the client-side code to interact with our WebSocket server.

  1. Create a directory named public and navigate into it:
mkdir public
cd public
  1. Create an index.html file:
touch index.html
  1. Add the following code to index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Real-Time Chat</title>
<style>
body { font-family: Arial, sans-serif; }
#chat { border: 1px solid #ccc; padding: 10px; height: 300px; overflow-y: scroll; }
#message { width: calc(100% - 60px); }
</style>
</head>
<body>
<h1>Real-Time Chat</h1>
<div id="chat"></div>
<input type="text" id="message" placeholder="Type a message...">
<button id="send">Send</button>

<script>
const ws = new WebSocket('ws://localhost:3000');

ws.onmessage = (event) => {
const chat = document.getElementById('chat');
const message = document.createElement('div');
message.textContent = event.data;
chat.appendChild(message);
};

document.getElementById('send').onclick = () => {
const messageInput = document.getElementById('message');
ws.send(messageInput.value);
messageInput.value = '';
};
</script>
</body>
</html>


Step 4: Run the Application

  1. Start your server:
node server.js
  1. Open your browser and navigate to http://localhost:3000.

You should see a simple chat interface where you can type and send messages. Open multiple tabs to test the real-time communication between clients.


Conclusion

Congratulations! You've built a basic real-time chat application using Node.js and WebSocket. This tutorial provides a foundation for creating more advanced chat applications with features like user authentication, message history, and private messaging. Feel free to expand and customize this project to fit your needs.

Stay tuned to our blog for more tutorials and tips on web development!


CodeGroundAI

CodeGroundAI is your all-in-one platform for seamless online coding. Whether you're a beginner or a pro, our IDE supports multiple programming languages, offers real-time collaboration, and provides a comprehensive toolkit for debugging, testing, and code execution.

Explore tools like the EPOCH Convertor, JSON Diff Checker, JWT Decoder, and Base64 Encoder/Decoder. With a real-time code-sharing platform and advanced comparison utilities, CodeGroundAI ensures you have everything you need for efficient development and accurate data handling.

Languages
  •  NodeJs
  •  Python
  •  Rust
  •  C++
  •  Java
  •  Golang
  •  Web
  •  MongoDB
  •  Redis
  •  Postgres
Tools
  •  Epoch Converter
  •  JSON Differentiator
  •  JWT Debugger
  •  Base64 Decode
  •  Base64 Encode
  •  Canvas
  •  Speed-Test
  •  Reads
Contact Us

Have questions or need support? Reach out to us for a smooth coding experience.

[email protected]

Connect with us on your favourite platform.

CodeGroundAI © 2024. All rights reserved.