node实现聊天室功能

源代码下载

下载node包:

npm install express --save
npm install socket.io --save

先完成页面

html

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>聊天室</title>
        <link rel="stylesheet" href="styles/main.css">
    </head>
    <body>
        <div class="wrapper">
            <div class="banner">
                <h1>聊天室</h1>
            </div>
            <div class="bottom">
                <div class="left">
                    <h2>成员 <span id="userCount">0</span></h2>
                    <ul></ul>
                </div>
                <div class="right">
                    <div id="historyMsg" class="content">
                        <ul></ul>
                    </div>
                    <div class="controls">
                        <textarea id="messageInput" name="textarea"></textarea>
                        <input id="sendBtn" type="button" value="发送">
                    </div>
                </div>
            </div>
            <div class="cover">
                <div>
                    <div id="info"></div>
                    <input type="text" id="nicknameInput" name="name" placeholder="请输入姓名">
                    <br>
                    <button id="query">确定</button>
                </div>
            </div>
        </div>
        
        <script src="http://10.51.16.15:9999/socket.io/socket.io.js"></script>
        <script src="js/jquery-1.10.2.min.js"></script>
        <script>
            $(function(){
                //实例并初始化我们的hichat程序
                var hichat = new HiChat();
                hichat.init();

                //昵称设置的确定按钮
                $('#query').on('click',function(){
                    var nickName = $('#nicknameInput').val();
                    //检查昵称输入框是否为空
                    if (nickName.length != 0) {
                        //不为空,则发起一个login事件并将输入的昵称发送到服务器
                        hichat.socket.emit('login', nickName);
                    }
                });

                $('#sendBtn').on('click', function() {
                    var msg = $('#messageInput').val();
                    $('#messageInput').val('');
                    if(msg.length != 0) {
                        hichat.socket.emit('postMsg', msg); //把消息发送到服务器
                        hichat._displayNewMsg('me', msg); //把自己的消息显示到自己的窗口中
                    };
                });

            });
            

            //定义我们的hichat类
            var HiChat = function() {
                this.socket = null;
            };

            //向原型添加业务方法
            HiChat.prototype = {
                init: function() {//此方法初始化程序
                    var that = this;

                    //建立到服务器的socket连接
                    this.socket = io.connect('http://10.51.16.15:9999');
                    //监听socket的connect事件,此事件表示连接已经建立
                    this.socket.on('connect', function() {
                        //连接到服务器后,显示昵称输入框
                        $('#info').text('请输入姓名');
                    });

                    this.socket.on('nickExisted', function() {
                        $('#info').text('名称已存在'); //显示昵称被占用的提示
                    });

                    this.socket.on('loginSuccess', function() {
                        $('.cover').hide();
                    });
                    
                    this.socket.on('system', function(nickName, userCount, type,users) {
                        console.log(nickName,userCount,type)

                        //判断用户是连接还是离开以显示不同的信息
                        var msg = nickName + (type == 'login' ? ' 进入房间' : ' 离开房间');
                        var html = '';
                        for(var i = 0;i<users.length;i++){
                            html += '<li>'+users[i]+'</li>'
                        }
                        $('.left ul').html(html);
                        
                        $('#historyMsg ul').append('<li class="chat-left" style="color:#f00;">'+msg+'</li>');
                        //显示在线人数
                        $('#userCount').text(userCount);
                    });

                    this.socket.on('newMsg', function(user, msg) {
                        that._displayNewMsg(user, msg);
                    });
                },
                _displayNewMsg: function(user, msg, color) {
                    var date = new Date().toTimeString().substr(0, 8);
                    if(user === 'me'){
                        $('#historyMsg ul').append('<li class="chat-right">'
                                    +'<div>'
                                       +' <div class="chat-content">'+
                                            msg
                                        +'</div>'
                                    +'</div>'
                                +'</li>');
                    }else{
                        $('#historyMsg ul').append('<li class="chat-left">'
                                +'<div>'
                                    +'<div id="userName">'+user+': <span>'+date+'</span></div>'
                                    +'<div class="chat-content">'+
                                        msg
                                    +'</div>'
                                +'</div>'
                            +'</li>');
                    }
                }
            };

        </script>
    </body>
</html>

css

*{
    margin:0;
    padding:0;
    list-style: none;
}
html,
body,
.wrapper{
    width:100%;
    height:100%;
    overflow: hidden;
}
.banner{
    width:100%;
    height:50px;
    border-bottom: 1px solid #000;
}
h1{
    font-size: 20px;
    font-weight: 100;
    text-align: center;
    line-height: 50px;
}
.bottom{
    width:100%;
    height:calc(100% - 50px);
    position: relative;
    clear: both;
}
.left{
    width:calc(20% - 1px);
    height:100%;
    border-right:1px solid #000;
    float: left;
}
.right{
    width:80%;
    height:100%;
    float: left;
}

h2{
    height:30px;
    font-size:15px;
    font-weight: bold;
    text-align: center;
    line-height: 30px;
}

.left li{
    padding: 10px 0 10px 20px;
}
.left li:hover{
    background: #8eafea;
}

.right .content{
    height: calc(80% - 1px);
    border-bottom:1px solid #000;
    overflow: hidden;
    padding:0 20px;
}
.right .content ul{
    clear: both;
    overflow: auto;
    height:100%;
}
.right .content li{
    margin-bottom: 10px;
    overflow: auto;
}
.right .content .chat-left > div{
    float: left;
}
.right .content .chat-right > div{
    float: right;
}
.right .content .chat-content{
    margin-left:20px;
}
.right .controls{
    width:100%;
    height:20%;
}
textarea{
    width:100%;
    height:calc(100% - 50px);
}
#sendBtn{
    width:150px;
    height:35px;
}

.cover{
    width:100%;
    height:100%;
    position: fixed;
    top:0;
    left:0;
    background: #fff;
}
.cover > div{
    width:300px;
    /*height:200px;*/
    background: rgba(0, 161, 255, 0.83);
    position: absolute;
    top:50%;
    left:50%;
    margin-left: -150px;
    margin-top:-87px;
    padding: 50px 0;
    text-align: center;
}
.cover input{
    height: 30px;
    width:200px;
}
.cover button{
    margin-top:10px;
    width:50px;
    height:30px;
}
#info{
    color:#f00;
}

服务器

var express = require('express'),
    app = express(),
    server = require('http').createServer(app),
    io = require('socket.io').listen(server); //引入socket.io模块并绑定到服务器
server.listen(9999);

var users = [];

//socket部分
io.on('connection', function(socket) {
    //在线统计,进入房间
    socket.on('login', function(nickname) {
        if (users.indexOf(nickname) > -1) {
            socket.emit('nickExisted');
        } else {
            socket.userIndex = users.length;
            socket.nickname = nickname;
            users.push(nickname);
            socket.emit('loginSuccess');
            io.sockets.emit('system', nickname, users.length, 'login',users);
        };
        console.log(nickname + '进入了房间')
        console.log(users)
    });

    //断开连接的事件
    socket.on('disconnect', function() {
        //将断开连接的用户从users中删除
        users.splice(socket.userIndex, 1);
        //通知除自己以外的所有人
        socket.broadcast.emit('system', socket.nickname, users.length, 'logout',users);
        console.log(socket.nickname + '退出了房间')
        console.log(users)
    });

    //接收新消息
    socket.on('postMsg', function(msg) {
        //将消息发送到除自己外的所有用户
        socket.broadcast.emit('newMsg', socket.nickname, msg);
        console.log(socket.nickname+'说:'+ msg)
    });
});

启动服务就可以了。

 safari解析时间报错
node操作mongoDB 入门 
上一篇:safari解析时间报错
下一篇:node操作mongoDB 入门
评论

如果我的文章对你有帮助,或许可以打赏一下呀!

支付宝
微信
QQ