What Are WebSockets?
WebSockets enable full-duplex, real-time communication between a client and server over a single persistent connection. They are ideal for chat applications, live notifications, and real-time dashboards on your Breeze.
Prerequisites
- A Breeze running Ubuntu 22.04 or later
- Node.js 18+ installed
- Nginx installed
Step 1: Create the WebSocket Server
mkdir /var/www/ws-server && cd /var/www/ws-server
npm init -y
npm install wsCreate server.js:
const { WebSocketServer } = require('ws');
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', (ws) => {
console.log('Client connected');
ws.on('message', (data) => {
wss.clients.forEach((client) => {
if (client.readyState === 1) {
client.send(data.toString());
}
});
});
ws.on('close', () => console.log('Client disconnected'));
});
console.log('WebSocket server running on port 8080');Step 2: Run with PM2
pm2 start server.js --name "ws-server"
pm2 save && pm2 startupStep 3: Configure Nginx for WebSocket Proxying
server {
listen 80;
server_name ws.yourdomain.com;
location / {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_read_timeout 86400;
}
}sudo ln -s /etc/nginx/sites-available/websocket /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
sudo certbot --nginx -d ws.yourdomain.comSecurity Considerations
- Always use WSS (WebSocket Secure) in production via your SSL certificate
- Implement authentication by validating tokens on the initial connection
- Set
proxy_read_timeouthigh enough to prevent Nginx from closing idle connections