Skip to content

Instantly share code, notes, and snippets.

@tsbits
Created February 6, 2015 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsbits/6d258e151393a1e637c2 to your computer and use it in GitHub Desktop.
Save tsbits/6d258e151393a1e637c2 to your computer and use it in GitHub Desktop.
Basic setup for Express + socket.io
// From http://stackoverflow.com/questions/9914816/what-is-an-example-of-the-simplest-possible-socket-io-example
var http = require('http'),
fs = require('fs'),
// NEVER use a Sync function except at start-up!
index = fs.readFileSync(__dirname + '/index.html');
// Send index.html to all requests
var app = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(index);
});
// Socket.io server listens to our app
var io = require('socket.io').listen(app);
// Send current time to all connected clients
function sendTime() {
io.sockets.emit('time', { time: new Date().toJSON() });
}
// Send current time every 10 secs
setInterval(sendTime, 10000);
// Emit welcome message on connection
io.sockets.on('connection', function(socket) {
socket.emit('welcome', { message: 'Welcome!' });
socket.on('i am client', console.log);
});
app.listen(3000);
<!-- From http://stackoverflow.com/questions/9914816/what-is-an-example-of-the-simplest-possible-socket-io-example -->
<!doctype html>
<html>
<head>
<script src='//code.jquery.com/jquery-1.7.2.min.js'></script>
<script src='//localhost:3000/socket.io/socket.io.js'></script>
<script>
var socket = io.connect('//localhost:3000');
socket.on('welcome', function(data) {
$('#messages').append('<li>' + data.message + '</li>');
socket.emit('i am client', {data: 'foo!'});
});
socket.on('time', function(data) {
console.log(data);
$('#messages').append('<li>' + data.time + '</li>');
});
socket.on('error', function() { console.error(arguments) });
socket.on('message', function() { console.log(arguments) });
</script>
</head>
<body>
<ul id='messages'></ul>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment