Skip to content

Instantly share code, notes, and snippets.

@Kaweechelchen
Forked from edds/README.md
Created December 27, 2016 08:28
Show Gist options
  • Save Kaweechelchen/df51f779f1ccf673d4277e2ce52a3a4e to your computer and use it in GitHub Desktop.
Save Kaweechelchen/df51f779f1ccf673d4277e2ce52a3a4e to your computer and use it in GitHub Desktop.
Socket.IO example to stream tweets on a topic

A simple example to create a websocket server and stream tweets about a pre-defined subject to the page.

Installation

$ npm install socket.io, twitter

Run

$ node ./app.js

Then open http://localhost:1337/ in a browser that supports websockets (or iDevice).

var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs'),
sys = require('sys'),
twitter = require('twitter');
app.listen(1337);
var twit = new twitter({
consumer_key: 'CONSUMER_KEY',
consumer_secret: 'CONSUMER_SECRET',
access_token_key: 'ACCESS_TOKEN_KEY',
access_token_secret: 'ACCESS_TOKEN_SECRET'
});
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
var twee = io.of('tweet');
twit.stream('statuses/filter', { track: 'javascript' }, function(stream) {
stream.on('data', function (data) {
io.sockets.emit('tweet', data.text);
console.log('.');
});
});
<!doctype html>
<title>Socket.io Demo</title>
<div id="tweets"></div>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('/'),
tweets = document.getElementById('tweets');
socket.on('tweet', function (data) {
tweets.innerHTML = tweets.innerHTML + '<br>' + data;
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment