由于工作需要,需要做一个贵金属IM系统 但是公司还不确定用什么来做,我竭力推荐nodejs 来做后端,前段用jquery 和 也很热的websocket 来交互,做了个小demo 下面直接上代码:
app.js:
var app = require('http').createServer(handler) , io = require('socket.io').listen(app) , fs = require('fs');
app.listen(9001);
function handler (req, res) {
console.log( __dirname );
fs.readFile( __dirname + '/send.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.emit('news', { hello: 'world' });
socket.on('send', function (data) {
socket.broadcast.emit('accept',data);
});
});
send.js:
$ = function(id){ return document.getElementById(id);}
//var havename = $(‘name’).value||undefined;
var socket = io.connect(‘http://localhost:9001’);
socket.on('news’, function (data) {
if( !$(‘name’).value ){
alert(‘hey:用户名不能为空’);
return false;
}
});
socket.on('accept’,function( data ){
var msg = $(“message”).innerHTML;
$(“message”).innerHTML = ‘’;
$(“message”).innerHTML += msg +’
'+data.name+’:’+data.news;
});
function send(){
if( havename = $(‘name’).value ){
var txt = $(‘textarea’).value;
socket.emit('send’, {name:havename,news:txt});
var msg = $(“message”).innerHTML;
$(“message”).innerHTML = ‘’;
$(“message”).innerHTML += msg +’
'+havename+’:’+txt;
}else{
alert(‘哦 来了个无名氏’);
return false;
}
}
send.html:
<script src="/socket.io/socket.io.js"></script> <script src="send.js"></script> <body>代码打包放在 sae 上了 大家可以简单瞅瞅 http://towei.sinaapp.com/keronode.rar