服务器使用NodeJS和Redis发送事件
Server Sent Events using NodeJS and Redis
我从Redis数据库接收更新(消息),我需要在客户端上实时显示这些消息,为此我使用SSE(服务器发送事件)。
所以,我的代码看起来是这样的:
客户端javascript:
var source = new EventSource('/updates');
source.addEventListener('pmessage', function(e) {
console.log('Event: ' + e.event);
console.log('Data: ' + e.data);
}, false);
服务器端(Node+Express):
req.socket.setTimeout(Infinity);
var redisURL = url.parse(process.env.REDISCLOUD_URL);
var client = redis.createClient(redisURL.port, redisURL.hostname, {ignore_subscribe_messages: true});
client.auth(redisURL.auth.split(":")[1]);
client.psubscribe('updates');
client.on('error', function (err) {
console.log('Error: ' + err);
});
client.on('psubscribe', function (pattern, count) {
console.log('psubscribe pattern: ' + pattern);
console.log('psubscribe count: ' + count);
});
client.on('pmessage', function (pattern, channel, message) {
console.log('pmessage pattern: ' + pattern);
console.log('pmessage from channel: ' + channel);
console.log('pmessage message: ' + message);
res.write("data: " + message + ''n'n');
});
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
res.write(''n');
我没有收到任何从服务器到客户端的更新(服务器正确地接收到来自redis的消息)。
如果我刷新服务器,我会收到以下错误:net::ERR_INCOMPLETE_CHUNKED_ENCODING
我是苏格兰和南方能源公司的新手,所以我可能做错了。我希望得到你的帮助。
解决方案是在每次需要向客户端发送消息时编写res.flush()
,在我的情况下:
client.on('pmessage', function (pattern, channel, message) {
console.log('pmessage pattern: ' + pattern);
console.log('pmessage from channel: ' + channel);
console.log('pmessage message: ' + message);
res.write("data: " + message + ''n'n');
res.flush();
});
已解决。
相关文章:
- 分派点击事件并保留击键修饰符
- 模糊事件的Javascript测试
- keyup事件处理程序更改焦点不适用于快速键入
- 使用 jQuery 的 .on 函数如何获取事件的原始元素
- 如何使Javascript动态html表及其上的事件
- 使用类从一个标记中双击事件
- 如何在未直接触发的情况下停止事件
- 如何在elfinder插件(一个文件管理器插件)上获得上传前事件
- 对iPad上的点击事件反应缓慢
- 事件和状态
- Fancybox是否将Click事件静音
- 主干-不管怎样,检查事件以前是否绑定过
- 从控制器返回后Ajax启动事件激发
- 如何从画布上的某个移动事件中获取X和Y
- 如何在 redis 中将 JS 对象传递给它自己的事件参数 - 连接事件上的哨兵
- 服务器发送事件未正确(刷新?)使用Flask和Redis与nginx前端
- 事件广播到特定用户(套接字).Io, redis, node)
- 如何使用node.js, socket .js触发事件在连接的客户端上触发.IO和redis
- 服务器使用NodeJS和Redis发送事件
- Redis消息事件中未引发TypeError