Skip to content

Instantly share code, notes, and snippets.

@robertklep
Created November 8, 2013 07:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save robertklep/5b299451d8bd450844a8 to your computer and use it in GitHub Desktop.
Save robertklep/5b299451d8bd450844a8 to your computer and use it in GitHub Desktop.
var http = require('http');
var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ port : 9001 });
http.createServer(function(req, res) {
res.end([
'<script>',
'var ws = new WebSocket("ws://localhost:9001");',
'ws.onmessage = function(ev) {',
' console.log("received message: " + ev.data);',
'};',
'setInterval(function() {',
' ws.send(Math.random());',
'}, 1000);',
'</script>'
].join('\n'));
}).listen(9000, function() {
console.log('Open http://localhost:9000/ in your browser');
});
wss.broadcast = function(data) {
for (var i in this.clients)
this.clients[i].send(data);
};
wss.on('connection', function(ws) {
ws.on('message', function(message) {
wss.broadcast('Broadcast message: ' + message);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment