Node.js Tutorial: Broadcasting Messages 🎯

beginner
7 min

Node.js Tutorial: Broadcasting Messages 🎯

Welcome to our comprehensive guide on Broadcasting Messages using Node.js! In this tutorial, we'll dive deep into the world of real-time communication, perfect for self-learners, students, and developers looking to upskill. Let's get started!

What is Broadcasting Messages? 📝

Broadcasting messages refers to the process of sending a single message to multiple clients or users in real-time. This is particularly useful in applications like chat platforms, live updates, and collaborative tools.

Setting up Node.js ✅

Before we dive into broadcasting messages, let's make sure you have Node.js installed. You can download it from official Node.js website (Don't worry, we don't use external links here!). Once installed, open your terminal/command prompt and check the version by typing:

bash
node -v

Introducing Socket.io 💡

For real-time communication in Node.js, we'll be using a popular library called Socket.io. Install it by running:

bash
npm install socket.io

Creating the Server 📝

Now, let's create a simple server using Express and Socket.io.

javascript
const express = require('express'); const app = express(); const http = require('http').createServer(app); const io = require('socket.io')(http); app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html'); }); io.on('connection', (socket) => { console.log('a user connected'); socket.on('disconnect', () => { console.log('user disconnected'); }); socket.on('chat message', (msg) => { console.log('message: ' + msg); io.emit('chat message', msg); }); }); http.listen(3000, () => { console.log('listening on *:3000'); });

The Client Side 💡

Create an index.html file in the same directory and add the following code:

html
<!DOCTYPE html> <html> <head> <title>Socket.io Chat</title> <script src="/socket.io/socket.io.js"></script> </head> <body> <ul id="messages"></ul> <form action=""> <input id="m" autocomplete="off" /><button>Send</button> </form> <script src="chat.js"></script> </body> </html>

Now, create a chat.js file and add the following code:

javascript
const socket = io(); const messageForm = document.querySelector('form'); const messageInput = document.querySelector('#m'); const messageList = document.querySelector('#messages'); messageForm.addEventListener('submit', (e) => { e.preventDefault(); if (messageInput.value) { socket.emit('chat message', messageInput.value); messageInput.value = ''; } }); socket.on('chat message', (msg) => { const li = document.createElement('li'); li.textContent = msg; messageList.appendChild(li); });

Now, if you run the server and open the index.html file in your browser, you can start sending and receiving messages! 🎉

Quiz 📝

Quick Quiz
Question 1 of 1

Which library do we use for real-time communication in Node.js?