Node.js+socket.io简单在线聊天

本文档介绍如何使用Node.js的Socket.IO库建立一个简单的在线聊天应用。通过在`e:/nodejs/easychat`创建`app.js`和`index.html`文件,设置好相关代码后,可以在多个浏览器实例或局域网中通过`http://ip:3000`进行实时通信。
摘要由CSDN通过智能技术生成

Node.js:0.10.31
在e:/nodejs/新建文件夹easychat
在easychat/下新建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(3000, function() {
    console.log('Listening at: http://localhost:3000');
});
  
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://cdn.staticfile.org/jquery/2.1.1-rc2/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>You have 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>
安装socket.io

npm install socket.io

这样就可以打开两个浏览器进行聊天了,局域网内访问http://ip:3000也可以实现聊天




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值