Skip to content

Instantly share code, notes, and snippets.

@pwFoo
Forked from tsh-code/Pub-Sub with websocket.js
Created August 11, 2024 14:37
Show Gist options
  • Save pwFoo/091857f68673382feb6e53b4d119c650 to your computer and use it in GitHub Desktop.
Save pwFoo/091857f68673382feb6e53b4d119c650 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