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://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:&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

Node.js学习(1):Node.js 和Socket.IO 实现chat,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。