打开和收听多个事件源

时间:2015-09-16 16:39:09

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

我有一个api,可以发送“数据”,“补丁”和“错误”等消息,我可以收听并回复。我试图用几个不同的查询来听几个(大约30个)这些(即听“亚特兰大老鹰队”和“纽约尼克斯队”)。 我不完全确定如何做到这一点。

我试图通过循环遍历数组来打开连接。然后,听取所有这些来源的事件。然而,for循环只是永远循环(我在2分钟内达到了请求限制:()

for(var i=0; i<teamList.length; i++){
      //open a new event source with the teamname
      var eventsource = new EventSource(streamdata + teamList[i] + streamtoken);
      //this was logged a million times :(
      eventsource.onopen = function(){
        console.log(teamList[i] + " connected!");
      };
eventsource.addEventListener('data', function(item) {
      //mess with 'item'
});

修改

这就是我尝试过的。我能够获取数据并弄乱它但它似乎永远循环。

for(var i=0; i<teamList.length; i++){
      var teamStream = global[eventsource[i]];
      var teamStream = new EventSource(streamdata + teamList[i] + streamtoken);

      teamStream.onopen = function(){
        console.log(teamStream + " connected!");
      };

      teamStream.addEventListener('data', function(item) {
      //set teamName as the query sent to api
      var data = JSON.parse(item.data);
      teamName = data.query;
      console.log('got data from ' + teamName);
      //set firebase node as the query sent to api
      var myFirebaseRef = new Firebase('https://shining-inferno-1085.firebaseio.com/' + teamName);
      //set initial data with returned api data
      myFirebaseRef.set(data);
    });

      teamStream.addEventListener('patch', function(patch) {
      var item = JSON.parse(patch.data);
      console.log("patch is " + item);
      if(patch.data[0].path !== "/time") {
          myFirebaseRef.push(patch.data);
       }
    });

    teamStream.addEventListener('error', function(e) {
      console.log('ERROR!');
      console.log(e.data);
      teamStream.close();
    });
  }

如果您能看到问题或者我是否在正确的轨道上,请告诉我

2 个答案:

答案 0 :(得分:0)

你不能在命名事件中使用一个EventSource吗?

event: userlogon\n
data: {"username": "John123"}\n\n

然后为每个事件处理不同的事件处理程序。

source.addEventListener('userlogon', function(e) { var data = JSON.parse(e.data); console.log('User login:' + data.username); }, false);

答案 1 :(得分:0)

可能您可以重写您的查询,以便您只有一个然后处理响应以将结果发送到30个«响应处理器»而不是30个查询。 本着这样的精神:

var myComplexQuery = ...
var teamStream = new EventSource(myComplexQuery);

teamStream.addEventListener('data', function(item) {
  var data = JSON.parse(item.data);
  var extractedData = {};
  extractedData = splitDataInto30Responses(data);
  for(var i=0; i<teamList.length; i++) { 
     // do whatever with your data
     var teamName = teamList[i];
     process(extractedData[teamName]);
  }

});