Skip to content

Instantly share code, notes, and snippets.

@devrnt
Last active May 22, 2019 18:41
Show Gist options
  • Save devrnt/4bddc1bcda784e6a625164e137fcbdf6 to your computer and use it in GitHub Desktop.
Save devrnt/4bddc1bcda784e6a625164e137fcbdf6 to your computer and use it in GitHub Desktop.
const config = require('../config/config');
const WebSocket = require('ws')
const wss = new WebSocket.Server({ port: config.port });
console.log('[WebSocket] Starting WebSocket server...');
wss.on('connection', (ws, request) => {
const clientIp = request.connection.remoteAddress;
console.log(`[WebSocket] Client with IP ${clientIp} has connected`);
// Broadcast to all connected clients
ws.on('message', message => {
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
console.log(`[WebSocket] Message ${message} was received`)
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment