Displaying streaming twitter on webpage with socket.io/node.js

前端 未结 2 987

I\'m trying to build a Twitter streaming web application using node.js socket.io and twit.

var express = require(\'express\')
  , app = express()
  , http = requ         


        
相关标签:
2条回答
  • The first issue is that you are constructing a new twitter listener each time a socket connection is opened. You should move that outside of the connection event. This is likely not ideal. I'm not sure how the twitter module is handling that internally but it likely actually is creating a new connection to their API each time a websocket connects.

    On the client side you jQuery could bit a bit different. If you just wanted to add a tweet to the page each time a tweet occurs, append a new tweet to the body element with $('body').append()

    See this gist for reference.

    0 讨论(0)
  • 2021-02-03 16:02

    Problem solved

    Here's the code without any mistakes : (server side)

    var express = require('express')
      , app = express()
      , http = require('http')
      , server = http.createServer(app)
      ,Twit = require('twit')
      , io = require('socket.io').listen(server);
    
    server.listen(8080);
    
    // routing
    app.get('/', function (req, res) {
    res.sendfile(__dirname + '/index.html');
    });
    
    var watchList = ['love', 'hate'];
     var T = new Twit({
        consumer_key:         ''
      , consumer_secret:      ''
      , access_token:         ''
      , access_token_secret:  ''
    })
    
    io.sockets.on('connection', function (socket) {
      console.log('Connected');
    
    
     var stream = T.stream('statuses/filter', { track: watchList })
    
      stream.on('tweet', function (tweet) {
    
        io.sockets.emit('stream',tweet.text);
    
    
      });
     });
    }); 
    

    (client-side)

     <script src="/socket.io/socket.io.js"></script>
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
      <script>
    
            var socket = io.connect('http://localhost:8080');
            socket.on('stream', function(tweet){
            $('#tweetd').append(tweet+'<br>');
            });
      </script>
      <div id="tweetd"></div>
    </div>
    
    0 讨论(0)
提交回复
热议问题