I have created a WebSocket server using socket.io. I have the following code
const express = require('express');
const socket = require('socket.io');
const app = express();
app.get('/socketTest', async (request, response) => {
io.sockets.in('testRoom1').emit('message', 'my message sample1');
response.send('Sample message sent via websocket');
});
const server = app.listen(3000, () => {});
const io = socket(server, {});
io.use(function(socket, next) {next();}).on('connection', function(client) {
client.on('subscribe', function(room) {
client.join(room.toLowerCase());
})
client.on('unsubscribe', function(room) {
client.leave(room.toLowerCase());
})
});
But after deploying my server on the different cluster, I didn't get the messages in the client properly.
So, I have added a Redis adapter using socket.io-redis library.
const express = require('express');
const socket = require('socket.io');
const redisAdapter = require('socket.io-redis');
const app = express();
app.get('/socketTest', async (request, response) => {
io.sockets.in('testRoom1').emit('message', 'my message sample1');
response.send('Sample message sent via websocket');
});
const server = app.listen(3000, () => {});
const io = socket(server, {});
io.adapter(redisAdapter({host: 'localhost', port: 6379}));
io.use(function(socket, next) {next();}).on('connection', function(client) {
client.on('subscribe', function(room) {
client.join(room.toLowerCase());
})
client.on('unsubscribe', function(room) {
client.leave(room.toLowerCase());
})
});
I got an error when trying to send a message from the server to clients.
http://localhost:3000/socketTest?roomname=testRoom1
(node:15304) UnhandledPromiseRejectionWarning: TypeError: callback is not a function
at Encoder.encode (E:\testProject\node_modules\socket.io-parser\index.js:135:5)
at RedisAdapter.broadcast (E:\testProject\node_modules\socket.io-redis\node_modules\socket.io-adapter\dist\index.js:102:45)
at RedisAdapter.broadcast (E:\testProject\node_modules\socket.io-redis\dist\index.js:267:15)
at Namespace.emit (E:\testProject\node_modules\socket.io\lib\namespace.js:234:16)
at E:\testProject\index.ts:38:21
at Generator.next (<anonymous>)
at E:\testProject\index.ts:8:71
at new Promise (<anonymous>)
at __awaiter (E:\testProject\index.ts:4:12)
at E:\testProject\index.ts:36:52
Any idea about this error? Is anything I have missed?