Skip to content

Instantly share code, notes, and snippets.

@jymcheong
Created June 10, 2019 03:24
Show Gist options
  • Save jymcheong/b918638fa2bb7c7fc72e75619f75353a to your computer and use it in GitHub Desktop.
Save jymcheong/b918638fa2bb7c7fc72e75619f75353a to your computer and use it in GitHub Desktop.
broadcast test
<!DOCTYPE html>
<html>
<head>
<title>Simple Echo Example</title>
<script>
var ws = new WebSocket('ws://127.0.0.1:8808/');
ws.onmessage = function(event) {
document.getElementById('msgBox').innerHTML = event.data;
}
function send()
{
ws.send(document.getElementById('outMsg').value);
}
</script>
</head>
<body>
<div id='msgBox'>Nothing sent yet!</div>
</body>
</html>
const WebSocket = require('ws');
var i = 0
const wss = new WebSocket.Server({ port: 8808 });
// Broadcast to all.
wss.broadcast = function broadcast(data) {
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
};
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
setInterval(function(){
wss.broadcast(i++)
}, 1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment