Skip to content

Instantly share code, notes, and snippets.

@edds
Created September 4, 2011 08:21
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save edds/1192510 to your computer and use it in GitHub Desktop.
Save edds/1192510 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>
@PterPmnta
Copy link

Sorry, what path is __dirname ??

@why
Copy link

why commented Apr 3, 2017

@PterPmnta It's the directory in which your app.js file is

@ifnullzero
Copy link

What does line 29 do?
var twee = io.of('tweet');
I don't see twee used anywhere else.

@ifnullzero
Copy link

I tried this code...it doesn't seem to work for me. When I change the console.log in app.js and make it display the incoming text (data.text) it shows correctly in the shell, but it does not get passed to the HTML page. Does this work for anyone else, if so how did you make it work?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment