-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathserver.js
66 lines (52 loc) · 1.84 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
var sys = require('sys'),
http = require('http'),
ws = require("./vendor/ws"),
base64 = require('./vendor/base64'),
arrays = require('./vendor/arrays');
// Command line args
var USERNAME = process.ARGV[2];
var PASSWORD = process.ARGV[3];
var KEYWORD = process.ARGV[4] || "iphone";
if (!USERNAME || !PASSWORD)
return sys.puts("Usage: node server.js <twitter_username> <twitter_password> <keyword>");
// Authentication Headers for Twitter
var auth = base64.encode(USERNAME + ':' + PASSWORD);
var headers = {
'Authorization' : "Basic " + auth,
'Host' : "stream.twitter.com"
};
var clients = [];
// Connection to Twitter's streaming API
var twitter = http.createClient(80, "stream.twitter.com");
var request = twitter.request("GET", "/1/statuses/filter.json?track=" + KEYWORD, headers);
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);
});
}
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(8080);