Created
October 12, 2011 19:25
-
-
Save nickfox/1282251 to your computer and use it in GitHub Desktop.
This file contains 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 app = require('http').createServer(handler) | |
, io = require('socket.io').listen(app) | |
, fs = require('fs') | |
app.listen(8137); | |
function handler (req, res) { | |
fs.readFile(__dirname + '/template.html', | |
function (err, data) { | |
if (err) { | |
res.writeHead(500); | |
return res.end('Error loading index.html'); | |
} | |
res.writeHead(200); | |
res.end(data); | |
}); | |
} | |
io.sockets.on('connection', function (socket) { | |
socket.on('message', function(msg) { | |
console.log(msg); | |
socket.broadcast.emit(msg); | |
}); | |
}); | |
//////////////////// | |
client side | |
//////////////////// | |
<script type="text/javascript" src="/socket.io/socket.io.js"></script> | |
<script type="text/javascript"> | |
$(document).ready(function() { | |
var entry_el = $('#entry'); | |
var socket = io.connect('ws://mywebsite.com:8137'); | |
socket.on('connect', function() { | |
console.log('connected.'); | |
}); | |
socket.on('message', function(msg) { | |
var data = msg.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"); | |
$('#log ul').append('<li>' + data + '</li>'); | |
window.scrollBy(0, 1000000000000000); | |
entry_el.focus(); | |
}); | |
entry_el.keypress(function(event) { | |
if (event.keyCode != 13) return; | |
var msg = entry_el.attr('value'); | |
if (msg) { | |
socket.send(msg); | |
entry_el.attr('value', ''); | |
} | |
}); | |
}); | |
</script> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment