Skip to content

Instantly share code, notes, and snippets.

@WebMaestroFr
Last active March 10, 2017 00:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WebMaestroFr/2a149a8611dbd4c911f8aed9bdd95662 to your computer and use it in GitHub Desktop.
Save WebMaestroFr/2a149a8611dbd4c911f8aed9bdd95662 to your computer and use it in GitHub Desktop.
Turn WebSocket messages into document Events.
var app = {
url: "ws://" + document.location.hostname
};
app.socket = new WebSocket(app.url + ":8082");
app
.socket
.addEventListener('message', function(e) {
var message = JSON.parse(e.data);
var event = new CustomEvent(message.type);
event.data = message.data;
document.dispatchEvent(event);
});
var WebSocket = require("ws");
var appSocket = new WebSocket.Server({perMessageDeflate: false, port: 8082});
appSocket.broadcast = function(type, data) {
var message = JSON.stringify({type: type, data: data});
appSocket
.clients
.forEach(function(client) {
if (client.readyState === WebSocket.OPEN) {
try {
client.send(message);
} catch (err) {
console.error("Broadcast Message", err);
}
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment