首页 > 代码库 > Node.js学习(1):Node.js 和Socket.IO 实现chat

Node.js学习(1):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://www.mamicode.com/"http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>    <script src=http://www.mamicode.com/"/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:&nbsp;<ul id="incomingChatMessages"></ul><br /><input type="text" id="outgoingChatMessage"></body></html>

开启服务器

node chat/app.js

打开两个chrome输入localhost:8080

转自:http://www.cnblogs.com/wancy86/archive/2013/04/28/socket-io_chat.html