Created
June 10, 2019 03:24
-
-
Save jymcheong/b918638fa2bb7c7fc72e75619f75353a to your computer and use it in GitHub Desktop.
broadcast test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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