首页 > 解决方案 > 使用redis适配器连接时Socket.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());
  })
});

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

因此,我使用 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

关于这个错误的任何想法?有什么我错过的吗?

标签: node.jswebsocketredissocket.iosocket.io-redis

解决方案


这个构造:

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

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

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

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

不打电话next(),你就会拖延每一个传入的连接。


推荐阅读