由于工作需要,需要做一个贵金属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 +’<br/>’+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 +’<br/>’+havename+’:’+txt; }else{ alert(‘哦 来了个无名氏’); return false; } }
send.html: <script src="/socket.io/socket.io.js"></script> <script src=“send.js”></script> <body> <div for=“name”>What’s your name:</div> <input type=“text” id=“name” name=“name” /> <div for=“name”>What’s your news:</div> <textarea type=“text” id=“textarea” name=“textarea”></textarea> <button onclick=“send()”>Send</button> <div id=“message” style=“color:red;”></div> </body>
代码打包放在 sae 上了 大家可以简单瞅瞅 http://towei.sinaapp.com/keronode.rar
<script src="send.js"></script>
这样写不对
对的 只是不规范而已
@pxiqnode 非也,现在的规范就是这样,默认的type=“text/javascript”