DEV Community

Cover image for 🗳️ NodeJs WebSocket Real Time Voting App
alexpaper
alexpaper

Posted on

🗳️ NodeJs WebSocket Real Time Voting App

This is the original question: how to create a voting app so that everyone is updated in real time,
at the very moment you vote?
This is the answer: via WebSocket!

BackEnd

In Nodejs you can install WS,
The WebSocket API tecnology allows you to create a communication client/server, and therefore to send
and receive data in real-time.

First of all you need to create a new WebSocketServer instance, you must indicate a Port number

import WebSocket, {WebSocketServer} from 'ws';

const wss = new WebSocketServer({port:8080});

Enter fullscreen mode Exit fullscreen mode

now it is very simple, when a user votes you have to make a broadcast of the updated data,
in this case an object with string values and an array of numbers

wss.clients.forEach(c=>{
    if(c.readyState === WebSocket.OPEN){
        c.send(JSON.stringify({time:datetime, message:`Updated data`, data:jsonData.data}))
    }
});

Enter fullscreen mode Exit fullscreen mode

FrontEnd

In the client side you need to do the same, first create a WebSocket instance pointing to the server

const ws = new WebSocket('ws://localhost:8080');

Enter fullscreen mode Exit fullscreen mode

now when the user gives the preference sends the data to the server that sends it back to all connected
clients and then updates the UI

ws.send(JSON.stringify({data:chartData.datasets[0].data}));

Enter fullscreen mode Exit fullscreen mode

very straight forward!

In this video guide you can see a super simple implementation of this, Have a nice day!

Video Guide
🆗 👋

Top comments (0)