-
-
Save pwFoo/091857f68673382feb6e53b4d119c650 to your computer and use it in GitHub Desktop.
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"); | |
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