Real-time communication is an essential part of modern web applications, enabling features like live chat, notifications, and collaborative tools. Socket.io is a powerful JavaScript library that allows bi-directional real-time communication between clients and servers. In this guide, we'll go through the basics of setting up Socket.io in a Node.js application.
What is Socket.io?
Socket.io is a library that enables real-time, event-based communication between the server and clients using WebSockets. It also provides fallbacks to other transport mechanisms (like long polling) when WebSockets are not supported.
Prerequisites
Before we begin, ensure you have the following installed:
- Node.js (Download it from nodejs.org)
- npm (Comes with Node.js)
Step 1: Setting Up a Basic Node.js Server
First, create a new project folder and initialize a Node.js project:
mkdir socketio-app
cd socketio-app
npm init -y
This creates a package.json
file, which manages dependencies for your project.
Step 2: Install Dependencies
We need Express (to create a server) and Socket.io:
npm install express socket.io
Step 3: Create the Server
Create a new file server.js
and add the following code:
const express = require("express");
const http = require("http");
const { Server } = require("socket.io");
const app = express();
const server = http.createServer(app);
const io = new Server(server);
app.get("/", (req, res) => {
res.send("Socket.io Server is Running");
});
io.on("connection", (socket) => {
console.log("A user connected");
socket.on("message", (msg) => {
console.log("Message received: ", msg);
io.emit("message", msg);
});
socket.on("disconnect", () => {
console.log("User disconnected");
});
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Explanation:
- We create an Express server wrapped with an HTTP server.
- Socket.io is initialized with the HTTP server.
- We listen for new connections and log when a user connects or disconnects.
- We handle incoming messages and broadcast them to all connected clients.
Step 4: Create a Simple Client
Now, let's create an index.html
file inside a public
folder and connect it to the server:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Socket.io Chat</title>
<script src="https://cdn.socket.io/4.0.1/socket.io.min.js"></script>
</head>
<body>
<h1>Simple Chat</h1>
<input id="message" type="text" placeholder="Type a message...">
<button onclick="sendMessage()">Send</button>
<ul id="messages"></ul>
<script>
const socket = io("http://localhost:3000");
function sendMessage() {
const message = document.getElementById("message").value;
socket.emit("message", message);
}
socket.on("message", (msg) => {
const li = document.createElement("li");
li.textContent = msg;
document.getElementById("messages").appendChild(li);
});
</script>
</body>
</html>
Explanation:
- We include the Socket.io client script.
- When a message is sent, it is emitted to the server.
- The server then broadcasts the message to all connected clients.
- Messages are displayed in a list on the page.
Step 5: Run the Server
Start the server with:
node server.js
Now, open index.html
in multiple browser tabs and test the chat functionality.
Conclusion
You've successfully set up a basic real-time chat application using Socket.io. This setup can be extended to build more complex applications like real-time notifications, multiplayer games, collaborative tools, and more.
In future posts, we'll explore rooms, namespaces, and authentication in Socket.io.
Have any questions? Let me know in the comments!
source: socket.io
0 Comments