WebSocket实例-Node.js和Socket.IO


费话就不多说了,先来说一个WebSocket的环境配置,用的是node.js和Socket.IO。

首先需要安装node.js,很简单。下载node.js,下载完成后双击安装,CMD打开命令窗口,指定到nodejs的安装目录。

安装Socket.IO也很容易,一条语包搞定,

npm install socket.io,等待安装完成就可以

WebSocket实例-Node.js和Socket.IO

在nodejs安装目录下,新建http.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(8888, function() {
    console.log('Listening at: http://localhost:8888');
});
 
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>

到此,所有的代码部分都已经完成,接下来就是运行了,

在命令窗口中,切换到nodejs的安装目录,运行如下指令:

>node http.js,效果如下图

WebSocket实例-Node.js和Socket.IO

现在我们运行两个浏览器(必须支持websocket的)就可以相互发消息了,效果图下图

WebSocket实例-Node.js和Socket.IO

Node.js+socket.io+聊天室源码

Node.js 的详细介绍:请点这里
Node.js 的下载地址:请点这里

推荐阅读:

Node.Js入门[PDF+相关代码]

Node.js安装与配置

Socket.IO 和 Node.js 入门

使用HTML5,WebSockets,nodejs和socket.io构建实时游戏

相关内容