2015-07-01 140 views
0

我收到从Redis的数据库更新(消息),我需要显示在客户端上进行实时的消息,为此我使用SSE(服务器发送事件)。服务器发送活动

所以,我的代码如下所示:

客户端的JavaScript:

var source = new EventSource('/updates'); 

source.addEventListener('pmessage', function(e) { 
    console.log('Event: ' + e.event); 
    console.log('Data: ' + e.data); 
}, false); 

服务器端(节点+快递):

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正确接收消息)。

如果我刷新服务器我收到此错误:网:: ERR_INCOMPLETE_CHUNKED_ENCODING

我新的SSE,所以也许我做错了。我希望在你的帮助下。

回答

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

解决。

+0

哇,它的工作原理!我有一个小问题:'res.flush()'做了什么?当我在'localhost'上运行客户端和服务器时,我的SSE工作,但是当我在不同的域上运行它们时(例如,'localhost'上的客户端向远程API服务器发送请求),会发生此错误。 'res.flush()似乎不在'express'的API中。 –