Socket.IO 和 Node.js 聊天程序

1、安装 node.js

2、安装 socket.io

    npm install socket.io

3、创建文件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);
    });
});

3、创建文件index.html 下载socket.io并引入socket.io.js

<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>

4、然后运行 app.js 文件:

node app.js

5、打开两个浏览器,访问 http://localhost:8080/ 地址开始互聊了
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值