简体   繁体   中英

Changing twitter stream predicates (Node.js, socket.io)

I am constructing a twitter stream with Twit where the user can change the search term from the client. The searchwords would be saved in a buffer and added to the stream in accordance with Twitters reconnection rules.

My code looks something like this:

var Twit = require('twit');

var T = new Twit({
    consumer_key:         'xxxxxxxxx'
  , consumer_secret:      'xxxxxxxxx'
  , access_token:         'xxxxxxxxx'
  , access_token_secret:  'xxxxxxxxx'
})

var searchStr = "orange";
var stream = T.stream('statuses/filter', { track: searchStr });

setInterval(function(){

    newSearchStr = getNewSearchStr();
    stream.stop();
    stream = T.stream('statuses/filter', { track:  newSearchStr});

},60*5*1000);


io.sockets.on('connection', function(socket) {

    //SAVE USER AND INTITIAL SEARCH CRITERIA
    // ...

    stream.on('tweet', function (tweet) {
        socket.emit('data',tweet);
    });

    socket.on('setSearchStr', function (searchStr) {

        //SAVE SEARCH TO BUFFER FOR getNewSearchStr() TO OBTAIN

    });
});

My problem is reinitializing the stream with new searches.

In the inteval-function stream.stop() does stop the stream (and stream.start() works too) but stream = T.stream(... opens a new connection instead of updating the current one. Thus the stream the user is listening to is disconnicted and the user stops recieving data until refreshing the browser.

Any ideas on how to do this with Twit? Any practical differences between clients? Other suggestions?

EDIT: The answer for a similiar question has a outdated link. I would really like to see the page with " instructions how change the predicates and making the user experience as smooth as possible "

Perhaps not best practise, but I eventually solved the problem by directly editing the stream object:

setInterval(function(){
    //check if criteria has changed
    if(stream.params.track != searchStr){
        console.log("Reconnecting with " + searchStr);

        stream.stop();
        stream.params.track = searchStr;
        stream.start();
    }
    else {
        console.log("Criteria unchanged");
    }
},60*5*1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM