Skip to content

Instantly share code, notes, and snippets.

@psycalc
Last active November 14, 2016 13:27
Show Gist options
  • Save psycalc/23458e066b76070d659bfb65138e4a70 to your computer and use it in GitHub Desktop.
Save psycalc/23458e066b76070d659bfb65138e4a70 to your computer and use it in GitHub Desktop.
Working example of WebSocket server on NODE.js ['ws']
//dependency: https://github.com/websockets/ws
//dependency installation: npm install --save ws
var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({
port: 8080
});
// Broadcast to all.
wss.broadcast = function broadcast(data) {
wss.clients.forEach(function each(client) {
client.send(data);
});
};
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
wss.clients.forEach(function each(client) {
//you Know about your message from server
// if (client !== ws)
client.send(message);
});
});
ws.send('Welcome on our WebSocketServer!)');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment