emit socket.io and sailsjs (Twitter API)

巧了我就是萌 提交于 2020-01-05 05:40:27

问题


I got the twits, I'm printing all of them ok in console, but I would like send the data to the view and I don't know how can I do it using socketio.

any idea?

var TwitterController = {

'index': function(req,res) {

var twitter = require('ntwitter');

var twit = new twitter({
  consumer_key: '...',
  consumer_secret: '...',
  access_token_key: '...',
  access_token_secret: '...'
});

twit.stream('statuses/filter', { track: ['dublin', 'spain']} , function(stream) {
  stream.on('data', function (data) {
    console.log(data.user.screen_name + ': ' + data.text);

    req.socket.emit('tweet', {
                    user: data.user.screen_name,
        text: data.text
    });

  });
});
       res.view();
},
};
module.exports = TwitterController;

and in the view I'm trying to print all the twits

<ul class="tw"></ul>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost:1337');


  jQuery(function($){
    var twList = $('ul.tw');
  });

  socket.on('tweet', function (data) {
    twList.prepend('<li>' + data.user + '</li>');
  });
</script>

回答1:


If you give Sails v0.9 a try, you'll have an easier time w/ this out of the box since the bundled example handles boilerplate connection logic for you.

The key is, instead of using res.view(), serve tweets with res.json(tweets).

In this example, you're using streams, so you can take advantage of res.pipe(stream).

Then you can use sails.io.js on the front-end to send a socket.io request to /twitter, and use the results for fun and profit.

The following front-end code assumes you're using the tiny client-side SDK (sails.io.js) bundled in Sails v0.9.x:

socket.get('/twitter', function (tweets) {
  console.log('Got the following tweets from the server :: ', tweets);
}

Keep in mind socket.get is just a convenience method on top of socket.emit that works with the Sails router out of the box. You can still do all the custom socket.io things you like if you have pubsub-specific code that you don't want to make accessible via HTTP.

sails.io.js also supports socket.post, socket.put, and socket.delete, with a similar API to the comparable jQuery AJAX methods (e.g. $.post)



来源:https://stackoverflow.com/questions/17705135/emit-socket-io-and-sailsjs-twitter-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!