我使用 socket.io 创建了一个 WebSocket 服务器。我有以下代码
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());
})
});
但是在不同的集群上部署我的服务器后,我没有正确地在客户端中获取消息。
因此,我使用 socket.io-redis 库添加了一个 Redis 适配器。
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());
})
});
尝试从服务器向客户端发送消息时出现错误。
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
关于这个错误的任何想法?有什么我错过的吗?