Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.