Created
September 9, 2013 13:27
-
-
Save cianclarke/6495568 to your computer and use it in GitHub Desktop.
Socket.io - replace application.js with this
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"> </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