Welcome to the exciting world of real-time web applications with Node.js and Socket.io! In this comprehensive guide, we'll learn how to set up Socket.io in a Node.js project, creating interactive, dynamic web experiences.
Socket.io is a JavaScript library that enables real-time, bidirectional communication between web clients and servers. It's essential for developing real-time web applications, like live chat, multiplayer games, and collaborative editing tools.
mkdir my-real-time-app
cd my-real-time-appnpm initFollow the prompts to set up your project details.
npm install socket.ioCreate a new file named server.js in your project folder.
// server.js
const express = require('express');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
app.use(express.static('public'));
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
const PORT = process.env.PORT || 3000;
http.listen(PORT, () => {
console.log(`listening on *:${PORT}`);
});In this code, we create an Express server and attach Socket.io to it.
Create a new folder named public in your project directory. Inside the public folder, create an index.html file.
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Real-time App</title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
socket.on('connect', () => {
console.log('Connected to server');
});
socket.on('disconnect', () => {
console.log('Disconnected from server');
});
</script>
</body>
</html>In the server-side code, we've set up an Express app and started the server. In the client-side code, we've connected to the server using Socket.io.
In the terminal, run your server:
node server.jsOpen another terminal and navigate to your project directory. Run:
open index.html(On Windows, use start index.html)
Now, open your browser and navigate to http://localhost:3000. You should see a simple HTML page with a console showing the connection and disconnection events.
In the next parts of this tutorial, we'll learn how to send messages between the client and the server in real-time. Stay tuned!
What is the purpose of the `io` object in server.js?