Last active
March 10, 2017 00:12
-
-
Save WebMaestroFr/2a149a8611dbd4c911f8aed9bdd95662 to your computer and use it in GitHub Desktop.
Turn WebSocket messages into document Events.
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
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); | |
}); |
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
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