I have copy pasted code from documentation. Still server is not able to receive events from emitter.
server.js
const { Server, Socket } = require("socket.io");
const { createClient } = require("redis");
const { createAdapter } = require("@socket.io/redis-adapter");
const io = new Server({ transports: ["websocket"] });
const pubClient = createClient({ url: "redis://localhost:6379" });
const subClient = pubClient.duplicate();
Promise.all([
pubClient.connect(),
subClient.connect(),
]).then(() => {
io.adapter(createAdapter(pubClient, subClient));
io.on("connection", (socket) => {
console.log("socket connected");
socket.on("time", (data) => {
console.log("data", data);
});
});
io.listen(3000);
});
emitter.js
const { Emitter } = require("@socket.io/redis-emitter");
const { createClient } = require("redis"); // not included, needs to be explicitly installed
const redisClient = createClient({ url: "redis://localhost:6379" });
const emitter = new Emitter(redisClient);
redisClient.connect().then(() => {
const io = new Emitter(redisClient);
setInterval(() => {
io.emit("time", new Date());
}, 5000);
});
Tried everything still not able to receive events on server. Events are successfully coming on redis but not propagating to server.
- Used namespaces
- Changed packages
You are thinking of the server as a client and trying to listen to the event in the server adapter but actually, the socket that will receive the emitter will be the client which is connected with the Redis adapter.
In Socket.IO data flow happens in this way.
Here the emitter is supposed to send the message to a topic to all the socket's server connected with redis adapter. Redis adapter will be the one connected with clients and will forward the event to socket server using redis pub-sub. Socket servers then will redirect the message to topic provided on which clients are currently connected.
The actual code will be like:
Socket Adapter
Socket Emitter
Socket Client