Polling app to support real-time updates Socket.IO

Polling app to support real-time updates Socket.IO

ยท

3 min read

To implement real-time updates in your Node.js and Express polling app, you can use the Socket.IO library. Socket.IO enables bidirectional communication between clients and servers, making it suitable for real-time applications. Below is a step-by-step guide to upgrade your polling app to support real-time updates without page refresh.

Step 1: Install Necessary Packages

Install the express, socket.io, and other necessary packages:

npm install express socket.io

Step 2: Set Up Your Project

Ensure you have your existing Node.js and Express polling app.

Step 3: Modify Your Express Server

In your server.js or app.js file, set up Socket.IO in conjunction with your existing Express app:

const express = require('express');
const http = require('http');
const socketIo = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketIo(server);

// Your existing Express setup goes here

// Socket.IO connection handling
io.on('connection', socket => {
  console.log('A user connected');

  // Handle events related to real-time updates here

  socket.on('disconnect', () => {
    console.log('User disconnected');
  });
});

const PORT = process.env.PORT || 3000;

server.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Step 4: Integrate Socket.IO with Your Polling Logic

In your polling routes (e.g., routes/poll.js), update the logic to emit real-time updates using Socket.IO. This example assumes you have a Poll model for managing polls:

const express = require('express');
const router = express.Router();
const Poll = require('../models/poll');

router.get('/', async (req, res) => {
  const polls = await Poll.find();
  res.render('polls/index', { polls });
});

router.post('/:id/vote', async (req, res) => {
  const pollId = req.params.id;
  const { option } = req.body;

  // Your existing voting logic

  // Emit real-time update to all connected clients
  io.emit('pollUpdate', { pollId, option });

  res.redirect(`/polls/${pollId}`);
});

module.exports = router;

Step 5: Update Your Frontend

Update your frontend (e.g., using HTML and JavaScript) to listen for real-time updates from the server and update the UI accordingly. If you're using a template engine like EJS, you can embed Socket.IO client code directly in your template.

<!-- views/polls/index.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Real-time Polling App</title>
</head>
<body>

  <!-- Your existing HTML goes here -->

  <script src="https://cdn.socket.io/4.1.3/socket.io.min.js"></script>
  <script>
    const socket = io();

    // Listen for real-time updates
    socket.on('pollUpdate', ({ pollId, option }) => {
      // Update your UI based on the real-time update
      console.log(`Poll ${pollId} updated with new vote for option ${option}`);
    });
  </script>
</body>
</html>

Step 6: Test the Implementation

  1. Start your Express server.

     node server.js
    
  2. Open your polling app in multiple browser tabs.

  3. Vote in one tab and observe real-time updates in all other tabs.

Congratulations! You've successfully upgraded your polling app to support real-time updates without page refresh using Socket.IO. Customize and expand this implementation based on your specific requirements.

Did you find this article valuable?

Support Revive Coding by becoming a sponsor. Any amount is appreciated!

ย