Skip to content

Instantly share code, notes, and snippets.

@tsh-code
Created January 19, 2020 16:19
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 tsh-code/c50bbe6ca1d84c2a3ec6ce86a61fdca3 to your computer and use it in GitHub Desktop.
Save tsh-code/c50bbe6ca1d84c2a3ec6ce86a61fdca3 to your computer and use it in GitHub Desktop.
const WebSocket = require("ws");
const redis = require("redis");
const subscriber = redis.createClient({
url: "redis://localhost:6379"
});
const publisher = subscriber.duplicate();
const WS_CHANNEL = "ws:messages";
const mockedUsers = [
{
id: 1,
firstname: "John",
lastname: "Doe"
}
];
const wss = new WebSocket.Server({ port: +process.argv[4] || 8080 });
subscriber.on("message", (channel, message) => {
if (channel === WS_CHANNEL) {
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
}
});
wss.on("connection", ws => {
console.log("new connection");
ws.on("message", data => {
const message = JSON.parse(data);
if (message.type === "get-users") {
ws.send(JSON.stringify(mockedUsers));
}
if (message.type === "broadcast") {
publisher.publish(WS_CHANNEL, JSON.stringify(mockedUsers));
}
});
});
subscriber.subscribe(WS_CHANNEL);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment