DEV Community

Manav Shandilya
Manav Shandilya

Posted on

Understanding Socket Programming with Node.js and Socket.IO

Socket programming enables real-time, bidirectional communication between a client and a server. In this blog, we'll explore the fundamentals of socket programming using Node.js and Socket.IO, while drawing examples from a Real-Time Tracker project.

What is Socket Programming?

Socket programming involves creating a connection between two nodes over a network, enabling continuous data exchange. It's essential for applications like chat apps, online games, and real-time trackers.

Why Use Socket.IO?

Socket.IO is a library that simplifies WebSocket implementation, providing features like event-driven communication, auto-reconnection, and cross-browser compatibility.

Core Concepts of Socket Programming

Establishing a Connection

A connection is established when the client and server communicate using WebSocket. In our project, this is done through:

const io = socketio(server);

io.on("connection", (socket) => {
    console.log("New user connected");
});
Enter fullscreen mode Exit fullscreen mode

Emitting and Listening to Events

Data is sent and received using custom events:

Client to Server: Sending user location.

navigator.geolocation.watchPosition((position) => {
    const { latitude, longitude } = position.coords;
    socket.emit("send-location", { latitude, longitude });
});
Enter fullscreen mode Exit fullscreen mode

Server to Client: Broadcasting location updates.

io.on("connection", (socket) => {
    socket.on("send-location", (data) => {
        io.emit("receive-location", { id: socket.id, ...data });
    });
});
Enter fullscreen mode Exit fullscreen mode

Handling Disconnections

Handling user disconnections ensures accurate tracking:

socket.on("disconnect", () => {
    io.emit("user-disconnected", socket.id);
});
Enter fullscreen mode Exit fullscreen mode

Rendering Data on the Client Side

The client listens for updates and updates the UI accordingly:

socket.on("receive-location", (data) => {
    const { id, latitude, longitude } = data;
    map.setView([latitude, longitude]);
    if (!markers[id]) {
        markers[id] = L.marker([latitude, longitude]).addTo(map);
    } else {
        markers[id].setLatLng([latitude, longitude]);
    }
});
Enter fullscreen mode Exit fullscreen mode

Real-Time Updates and Map Integration

By combining Leaflet.js with Socket.IO, we display real-time user positions on a map.

const map = L.map("map").setView([0, 0], 16);
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
    attribution: "OpenStreetMap",
}).addTo(map);
Enter fullscreen mode Exit fullscreen mode

Conclusion

Socket programming enables real-time communication in web applications. Using Node.js and Socket.IO simplifies this process, as demonstrated through our Real-Time Tracker example. Understanding the core concepts will help you build scalable, interactive applications with ease.

Happy coding! 🚀

Top comments (0)