I've got socket.io set up with node.js. My scenario is a user/client supplies a twitter screen_name to follow, and then I need to subscribe to that twitter stream using the supplied screen_name (for some asinine reason the API requires a user_id instead of a screen_name).
I've run into a sequence problem where I have to subscribe to the stream before I know the screen_name (and subsequently the user_id):
var tweetStream;
io.sockets.on('connection', function connect( socket )
{
socket.on('subscribe', function(data)
{
twitter.get(
'statuses/user_timeline',
{ "screen_name": data.screen_name },
function getTweets( err , tweets )
{
// …
// var user_id …
tweetStream = twitter.stream('statuses/filter', { "follow": user_id });
console.log('\n','tweetStream: ', tweetStream, '\n');
tweetStream.on('tweet', function onTweet(tweet)
{
console.log( '\ntweetStream -> new tweet: ', tweet, '\n' );
io.sockets.in( data.screen_name ).emit('tweets', tweet );
});
}
);
});
}
The above does not subscribe to the tweetstream and does not produce an error. If I move the tweetStream code outside of socket.io and hard-code a user_id (because it's otherwise not available), it works:
var tweetStream;
io.sockets.on('connection', function connect( socket )
{
…
}
tweetStream = twitter.stream('statuses/filter', { "follow": 6253282 });
console.log('\n','tweetStream: ', tweetStream, '\n');
tweetStream.on('tweet', function onTweet(tweet)
{
console.log( '\ntweetStream -> new tweet: ', tweet, '\n' )
io.sockets.in( tweet.user.screen_name ).emit('tweets', data );
});
EDIT
The tweetStream
objects in both cases are identical (compared via FileMerge).
Here's a Gist with the complete code.
The problem was that the twitter
instance needs to be instantiated inside the socket.on('subscribe') callback:
// …
var io = require('socket.io').listen(server);
var Twit = require('twit');
io.sockets.on('connection', function connect( socket )
{
//…
socket.on('subscribe', function subscribe( data )
{
var twitter = new Twit({ … });
// …
});
//…
});
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.