Skip to content

Instantly share code, notes, and snippets.

@cianclarke
Created September 9, 2013 13:27
Show Gist options
  • Save cianclarke/6495568 to your computer and use it in GitHub Desktop.
Save cianclarke/6495568 to your computer and use it in GitHub Desktop.
Socket.io - replace application.js with this
var fs = require('fs');
var util = require('util');
var http = require('http');
// index.html
var html = [
'<html><head><script src="/socket.io/socket.io.js"></script>',
'<script>',
'var socket = io.connect(document.location.href);',
'socket.on("time", function (data) {',
' document.getElementById("time").innerHTML= data.time;',
' var d = new Date();',
' socket.emit("clientTime", { time: d.toString() });',
'});',
'</script></head><body>',
'<div style="border:1px solid #ccc" id="time">&nbsp;</div>',
'<body></html>'];
// http server
function server (req, res) {
console.log(req.url);
res.writeHead(200);
res.end(html.join('\n'));
}
// Socket.io setup
var app = require('http').createServer(server);
var io = require('socket.io').listen(app);
io.set('log level', 1);
app.listen(process.env.FH_PORT || 8080);
// Socket.io events
io.sockets.on('connection', function (socket) {
// emit the time every second
setInterval(function(){
var d = new Date();
socket.emit('time', { time: d.toString() });
}, 1000);
// write the clients time to stdout
socket.on('clientTime', function (data) {
console.log("client time: " + util.inspect(data));
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment