In this tutorial, we'll be learning how to build a real-time chat application using Socket.io. This chat application will allow users to send and receive messages instantly.
You will learn how to:
Prerequisites:
We'll start by setting up a server using Node.js and Express. Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.
// Import express and create an app
const express = require('express');
const app = express();
// Define a route handler for the default home page
app.get('/', (req, res) => {
res.send("Hello World!");
});
// Start the server on port 3000
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Socket.io enables real-time, bidirectional and event-based communication. It works on every platform, browser, or device, focusing equally on reliability and speed.
// Import socket.io with a connection to a server obtained from a http server
var server = require('http').createServer(app);
var io = require('socket.io')(server);
// Listen on the connection event for incoming sockets
io.on('connection', (socket) => {
console.log('a user connected');
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
Now we'll implement the core functionality of our chat app: sending and receiving messages.
io.on('connection', (socket) => {
console.log('a user connected');
// Listen for chat message event
socket.on('chat message', (msg) => {
console.log('message: ' + msg);
// Emit the message to all connected clients
io.emit('chat message', msg);
});
});
In this code snippet, we listen for the 'chat message' event, log the message to the console, and then emit the message to all connected clients.
We also want to handle the case where a user disconnects from the chat.
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('chat message', (msg) => {
console.log('message: ' + msg);
io.emit('chat message', msg);
});
// Listen for disconnect event
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
In this tutorial, we learned how to build a real-time chat application using Socket.io. We covered setting up a server with Node.js and Express, integrating Socket.io, and sending/receiving messages.
Next steps for learning would be to explore more features of Socket.io, like rooms and namespaces, and to experiment with storing messages in a database.
Additional resources include the Socket.io Documentation.
Each of these exercises can be solved by applying what we've already learned and looking up additional information in the Socket.io documentation. For further practice, consider exploring other real-time data use-cases, like live updates in a dashboard application.