简体   繁体   English

如何使用Node.js和Websockets创建Twitter流?

[英]How can I create a Twitter stream using Node.js and Websockets?

A few months ago (August 2011) I successfully created a node.js websockets server which connected to Twitter's Streaming API using basic HTTP user/password authentication. 几个月前(2011年8月),我成功创建了一个node.js websockets服务器,该服务器使用基本的HTTP用户/密码身份验证连接到Twitter的Streaming API To do this, I employed Andre Goncalves' twitter-nodejs-websocket library. 为此,我使用了Andre Goncalves的twitter-nodejs-websocket库。

Since creating this working implementation, Twitter has eliminated access to the streaming API via basic HTTP auth, in favor of OAuth . 自创建此可行的实现以来,Twitter取消了通过基本HTTP身份验证对流API的访问,转而使用OAuth After this shift, I utilized Ciaran Jessup's node-oauth library, which has successfully given me access to the Streaming API again (when I run the server I am successfully outputting the tweets via console.log(tweet) -- see below ). 经过这一转变后,我利用了Ciaran Jessup的node-oauth库,该库成功地使我再次访问了Streaming API(当我运行服务器时,我已经通过console.log(tweet)成功输出了tweet-参见下文)。

The problem now is that my websockets server is no longer working. 现在的问题是我的websockets服务器不再工作。 When I run my server from the command line and hit the client web page from the browser, the websocket "onclose" event is immediately fired. 当我从命令行运行服务器并从浏览器访问客户端网页时,立即触发websocket“ onclose”事件。

I've tried everything I can think of to get this working. 我已经尽我所能使一切正常。 Any help would be very greatly appreciated! 任何帮助将不胜感激!

server.js server.js

var sys    = require('sys'),
    http   = require('http'),
    ws     = require("./vendor/ws"),
    base64 = require('./vendor/base64'),
    arrays = require('./vendor/arrays')

var OAuth = require('./oauth/oauth').OAuth;

var consumer_key        = '[...]'; //removed for obvious security reasons...
var consumer_secret     = '[...]';
var access_token        = '[...]';
var access_token_secret = '[...]';

oa = new OAuth("https://twitter.com/oauth/request_token",
                "https://twitter.com/oauth/access_token", 
                consumer_key,
                consumer_secret,
                "1.0A",
                null,
                "HMAC-SHA1");

var request = oa.get("https://stream.twitter.com/1/statuses/filter.json?track=google", access_token, access_token_secret );

// Response Parsing -------------------------------------------- //

var clients = [];
var message = "";

request.addListener('response', function (response) {

    response.setEncoding('utf8');

    response.addListener("data", function (chunk) {

        message += chunk;

        var newlineIndex = message.indexOf('\r');
        // response should not be sent until message includes '\r'.
        // Look at the section titled "Parsing Responses" in Twitter's documentation.
        if (newlineIndex !== -1) {
            var tweet = message.slice(0, newlineIndex);

            clients.forEach(function(client){
                // Send response to all connected clients
                client.write(tweet);
            });

            // this just tests if we are receiving tweets -- we are: terminal successfully outputs stream //
            var pt = JSON.parse(tweet);
            console.log('tweet: ' + pt.text);
        }
        message = message.slice(newlineIndex + 1);
    });

});
request.end();

// Websocket TCP server

ws.createServer(function(websocket){
  clients.push(websocket);
  websocket.addListener("connect", function(resource){
    // emitted after handshake
    sys.debug("connect: " + resource);
  }).addListener("close", function(){
    // emitted when server or client closes connection
    clients.remove(websocket);
    sys.debug("close");
  });
}).listen(8081);


// This basic http server works, so we know this port is open.
//
// var http = require('http');
// http.createServer(function (req, res) {
//   res.writeHead(200, {'Content-Type': 'text/plain'});
//   res.end('Hello World\n');
// }).listen(8081);

client code 客户代码

<script type="text/javascript" charset="utf-8">
    ws = new WebSocket("ws://ec2-67-202-6-10.compute-1.amazonaws.com:8081");
    ws.onmessage = function(evt) {
        console.log('tweet')
    };
    ws.onclose = function() {
        console.log("socket closed");
    };
    ws.onopen = function() {
        console.log("connected...");
    };
</script>

Maybe you updated the browser? 也许您更新了浏览器? The websocket spec is chaning rapidly. Websocket规范正在迅速变化。 Anyway, I'd propose using socket.io because it will even still work with fallbacks if the browser is outdated or websockets got incompatible again or a crappy proxy is preventing websockets from working. 无论如何,我建议使用socket.io,因为如果浏览器过时或websockets再次不兼容,或者糟糕的代理阻止了websockets的工作,它甚至仍然可以使用回退。

Have a look at this sample event stream (it uses server sent events) from a twitter stream: 看一下来自Twitter流的此示例事件流(它使用服务器发送的事件):

https://github.com/chovy/nodejs-stream https://github.com/chovy/nodejs-stream

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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