我正在尝试解决与 Nest API 和不支持流式传输的服务 (ST) 之间的流式传输有关的问题。
为了解决这个问题,我在 Sails 上构建了一个服务,该服务从 ST 接收包含 Nest 令牌的发布请求,然后触发 EventSource 事件侦听器,将数据发送回 ST。
它在很大程度上基于此处的 Nest rest-streaming 示例: https ://github.com/nestlabs/rest-streaming ,我的代码如下:
startStream: function(req, res) {
var nestToken = req.body.nestToken,
stToken = req.body.stToken,
endpointURL = req.body.endpointURL,
source = new EventSource(sails.config.nest.nest_api_url + '?auth=' + nestToken);
source.addEventListener('put', function(e) {
var d = JSON.parse(e.data);
var data = { devices: d.data.devices, structures: d.data.structures},
config = { headers : {'Authorization': 'Bearer ' + stToken}};
sendData(endpointURL, data, config);
});
source.addEventListener('open', function(e) {
console.log("Connection opened");
});
source.addEventListener('auth_revoked', function(e){
console.log("Auth token revoed");
});
source.addEventListener('error', function(e) {
if (e.readyState == EventSource.CLOSED) {
console.error('Connection was closed! ', e);
} else {
console.error('An unknown error occurred: ', e);
}
}, false);
}
};
我预见的问题是,一旦节点服务器收到请求,它就会启动事件侦听器,但是我无法终生弄清楚如何杀死事件侦听器。
如果我无法找到阻止这种情况的方法,那么每个 EventListener 都会无限期地运行,这显然是不合适的。
有没有人对如何克服这个问题有任何建议?