昨天晚上花了一小时,体验了下快速极限编程,使用nodejs express + socket.io + jquery 制作一个极简单的聊天服务器,socket.io果然对于简单而强大
zengke:mchat$ date Mon Nov 28 22:46:02 CST 2011 ... zengke:mchat$ date Mon Nov 28 23:40:30 CST 2011
服务器端代码 node.js
var express = require('express'); var app = express.createServer(); var io = require('socket.io').listen(app); app.configure(function () { app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.logger()); app.use(express.bodyParser()); app.use(express.cookieParser()); app.use(express.session({ secret: "skjghskdjfhbqigohqdioukd", })); }); var conns = {}; io.sockets.on('connection', function (socket) { var cid = socket.id; for(var ccid in conns) { var soc = conns[ccid]; soc.emit('join', {cid: socket.id}); } conns[cid] = socket; socket.on('disconnect', function () { delete conns[cid]; for(var cid in conns) { var soc = conns[cid]; soc.emit('quit', {cid: cid}); } }); socket.on('say', function (data) { data.cid = cid; for(var ccid in conns) { var soc = conns[ccid]; soc.emit('broadcast', data); } }); }); app.get('/', function (req, res) { res.sendfile(__dirname + '/public/index.html'); }); app.use('/public', express.static(__dirname + '/public')); app.listen(3000); console.log('daemon start on http://localhost:3000');
浏览器端javascript
var socket = io.connect("http://localhost"); socket.on('quit', function (data) { status('Client ' + data.cid + ' quits!'); }); socket.on('join', function (data) { status('Client ' + data.cid + ' joins!'); }); socket.on('broadcast', function (data) { $('#thread').append($('').html('client ' + data.cid + ' says:
' + data.w)); }); function say() { var words = $('#text').val(); if($.trim(words)) { socket.emit('say', {w: words}); $('#text').val(''); } } function status(w) { $('#status').html(w); } function initialize() { $(document).delegate('textarea', 'keydown', function (evt) { //console.info(evt.keyCode); if(evt.keyCode == 13 && evt.ctrlKey) { $('#send').focus().click(); } }); }
页面HTML代码
Micro Chat