I would have fun creating projects that update in an instant. Receiving real-time alerts is unbelievably satisfying because you can press something, and the updates are instantly present. Ever been curious how apps can do that? Me too, until I dabbled in WebSockets on my VPS to make my life sooo much easier.
Why WebSockets Are Awesome for Real-Time Alerts
WebSockets connect users and servers together just like two people on a phone call. They can both speak whenever they would like. There is nothing that needs to be refreshed, as the situation feels seamless. I had used long-polling for a while, and I now can genuinely ask myself "Why didn't I make the switch sooner?"How Do WebSockets Work On A VPS?
In simple terms, you open a WebSocket connection, and the server keeps the socket open for any future communications. When something new occurs on the server, whether is a message, alert, update, or other, the server sends the data in an instant. No equivocation, and the whole time you are not repeatedly pinging. When you start to see updates instantly, it feels remarkable.Basic Setup You Can Use
I prefer to keep things simple seeing as you can get more complex options if you want. So here is my standard set up on a VPS:- Node.js + ws package as the WebSocket server
- Nginx as a reverse proxy
- A simple eventing system to push updates
Why I Use WebSockets over Other Options
I have tried using Server-Sent Events (SSE) if you have also done this. It works but WebSockets gives you more options:- Two-way communication (both sides can talk)
- Less overhead on the connection
- Much better control of events
- Better scalability with a load balancer
Effortlessly Sending Notifications In Real Time
When I designed my first notification system, I kept it simple and focused on three things:- Fast connection
- Simple messages
- Clean client code
Keeping the System Safe And Running Smoothly
Real-time event systems can fail upon connection loss, and if you haven’t built your version of that system correctly, the connections will fail repeatedly. I always do the following:- Check and verify every connection
- Limit the size of each message
- Log any connection error reconnect attempts
- Run your web socket server in a process manager (such as PM2)