node.js - 使用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
关于这个错误的任何想法?有什么我错过的吗?
解决方案
这个构造:
io.use(function(socket, next) {})
是不正确的。这是中间件。如果您调用io.use()
并希望继续进行常规处理,则必须next()
在传递它的函数体中调用。由于您显然没有对此做任何事情,因此您可能应该将其删除。
如果你想实际使用这个中间件:
io.use(function(socket, next) {
// do something here, then call next()
next();
});
不打电话next()
,你就会拖延每一个传入的连接。
推荐阅读
- javascript - React-Redux - onClick 在每次状态更改时触发
- arrays - 用用户输入替换字符串中的单词 [RUBY]
- jquery - 使用新的 LESS 文件重新加载页面
- ruby - Ruby:错误:当我给出正确数量的参数时,参数数量错误(给定 1,预期为 0)
- swift - Swift 4 相机视图出现在 iPad 上
- azure - microsoft-graph Azure AD登录预览日志修改
- ruby-on-rails - Spring 为每次测试运行重新开始
- vaadin - Vaadin 10+:如何处理未捕获的异常?
- apache-spark - Spark RDD 以独占方式按键分区
- python - 如何在熊猫数据框中查找连续相同字符串值的计数?