【问题标题】:Server Sent Events using NodeJS and Redis服务器使用 NodeJS 和 Redis 发送事件
【发布时间】:2015-07-01 11:08:43
【问题描述】:

我从 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

我是 SSE 的新手,所以我可能做错了。希望得到您的帮助。

【问题讨论】:

    标签: javascript node.js server-sent-events


    【解决方案1】:

    解决方案是每次需要向客户端发送消息时写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();
      });
    

    解决了。

    【讨论】:

    • 哇它好用!我有一个小问题:res.flush() 是做什么的?当我在localhost 上运行客户端和服务器时,我的 SSE 可以工作,但是当我在不同域上运行它们时(例如,localhost 上的客户端向远程 API 服务器发送请求)会发生此错误。 res.flush() 似乎不在 express 的 API 中。
    猜你喜欢
    • 2020-07-15
    • 2016-04-18
    • 1970-01-01
    • 2017-01-26
    • 2015-10-26
    • 2013-12-29
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多