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!
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.
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:
node -vFor real-time communication in Node.js, we'll be using a popular library called Socket.io. Install it by running:
npm install socket.ioNow, let's create a simple server using Express and Socket.io.
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');
});Create an index.html file in the same directory and add the following code:
<!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:
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! 🎉
Which library do we use for real-time communication in Node.js?