插座.使用redis适配器连接时,IO返回回调错误



我使用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());
})
});

但是在将我的服务器部署到不同的集群后,我没有正确地在客户端获取消息。

所以,我添加了一个Redis适配器使用套接字。io-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/套接字?roomname = testRoom1

(node:15304) UnhandledPromiseRejectionWarning: TypeError: callback is not a function
at Encoder.encode (E:testProjectnode_modulessocket.io-parserindex.js:135:5)
at RedisAdapter.broadcast (E:testProjectnode_modulessocket.io-redisnode_modulessocket.io-adapterdistindex.js:102:45)
at RedisAdapter.broadcast (E:testProjectnode_modulessocket.io-redisdistindex.js:267:15)
at Namespace.emit (E:testProjectnode_modulessocket.iolibnamespace.js:234:16)
at E:testProjectindex.ts:38:21
at Generator.next (<anonymous>)
at E:testProjectindex.ts:8:71
at new Promise (<anonymous>)
at __awaiter (E:testProjectindex.ts:4:12)
at E:testProjectindex.ts:36:52

你知道这个错误是怎么回事吗?我错过什么了吗?

这个结构:

io.use(function(socket, next) {})

不正确。这就是中间件。如果调用io.use()并希望正常处理继续进行,则必须在传递给它的函数体中调用next()。既然你显然没有对它做任何事情,你可能应该删除它。

如果你想实际使用这个中间件:

io.use(function(socket, next) {
// do something here, then call next()
next();
});

如果不调用next(),您将阻塞所有传入的连接。

最新更新