Node.js 和Socket.IO 实现chat
使用 Node.js 和 Socket.IO 构建简单的聊天程序
在node.js根目录下创建文件夹chat,里面添加两个文件:app.js和index.html
app.js
var fs = require('fs') , http = require('http') , socketio = require('socket.io'); var server = http.createServer(function(req, res) { res.writeHead(200, { 'Content-type': 'text/html'}); res.end(fs.readFileSync(__dirname + '/index.html')); }).listen(8080, function() { console.log('Listening at: http://localhost:8080'); }); socketio.listen(server).on('connection', function (socket) { socket.on('message', function (msg) { console.log('Message Received: ', msg); socket.broadcast.emit('message', msg); }); });
index.html
<html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script src="/socket.io/socket.io.js"></script> <script> $(function(){ var iosocket = io.connect(); iosocket.on('connect', function () { $('#incomingChatMessages').append($('<li>Connected</li>')); iosocket.on('message', function(message) { $('#incomingChatMessages').append($('<li></li>').text(message)); }); iosocket.on('disconnect', function() { $('#incomingChatMessages').append('<li>Disconnected</li>'); }); }); $('#outgoingChatMessage').keypress(function(event) { if(event.which == 13) { event.preventDefault(); iosocket.send($('#outgoingChatMessage').val()); $('#incomingChatMessages').append($('<li></li>').text($('#outgoingChatMessage').val())); $('#outgoingChatMessage').val(''); } }); }); </script> </head> <body> Incoming Chat: <ul id="incomingChatMessages"></ul> <br /> <input type="text" id="outgoingChatMessage"> </body> </html>
开启服务器
node chat/app.js
打开两个chrome输入localhost:8080
这样就看到效果了,然后你可以慢慢研究代码了,再然后就洗洗睡吧。
使用的源码来自http://www.open-open.com/lib/view/open1337216216557.html