Express结合Socket.io实现聊天室功能

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_40629244/article/details/102766760

就在刚才,写了一篇 《Node.js中运用socket.io实现智能回复机器人与聊天室功能》 发现一瞬间看的人还挺多,不过这篇博客只是讲解了一些实现原理,现在运用Node的Express框架给大家实现一下聊天室。

首先是服务端的代码

// 引入Express
var express=require('express');
// 创建服务
var app=express();
// 引入封装的mongoDB数据库,包含增、删、改、查功能
var DB=require('./module/db.js');

// 1.引入Http模块,传入express生成服务器
var server = require('http').Server(app);
// 2.引入sockit.io传入生成的服务器
var io = require('socket.io')(server);

// 使用Ejs模板引擎
app.set('view engine','ejs');
// 配置静态文件访问地址
app.use(express.static('public'));
// 监听端口
server.listen(8000);

// 登录页的路由
app.get('/',function(req,res){
    res.render('login');
});
// 聊天页面的路由
app.get('/chat',function(req,res){
    var name=req.query.name;
    res.render('chat',{
        name:name
    });
});

// 3.建立socket链接
io.on('connection',function(socket){
    // 4.监听客户端发送的消息
    socket.on('message',function(data){
        // 5.将消息发送给所有建立链接的客户端
        io.emit('message',data);
    })
})

上面的代码中有引入一个封装的MongoDB数据库,大家可以参考一下 《Koa封装MongoDB数据库》里面的第二段代码的实现,这里代码就不做展示了,如果你用的是MySQL数据库也可以换成MySQL数据库。

以下是客户端的代码,主要分成两个页面,一个是输入用户名的登录页,一个是聊天室页面,用户必须首先登录才能进入聊天室,否则在聊天室页面无法显示发送消息的人是谁。

以下是登录聊天室页面的Demo

<!DOCTYPE HTML>
<html>

<head>
    <title>登录</title>
    <style>
        html {
            height: 100%;
            background-color: #1B1C3B;
        }

        .box {
            width: 400px;
            height: 60px;
            display: flex;
            margin: 200px auto;
        }

        .box input[type='text'] {
            flex: 1;
            height: 60px;
            border: 1px solid #eee;
        }

        .box button {
            width: 100px;
            height: 64px;
            background: orange;
            color: #fff;
            border: none;
            cursor: pointer;
        }
    </style>
    <script src="jquery-1.11.3.min.js"></script>
    <script>
        $(function () {
            // 点击登录
            $('.login').click(function () {
                var name = $('#name').val();
                if (name) {
                    // 跳转到聊天室
                    location.href = '/chat?name=' + name;
                } else {
                    alert('请输入您的名称');
                }
            })
        })
    </script>
</head>

<body>

    <div class="box">
        <input type="text" placeholder="请输入您的姓名" id="name" />
        <button class="login">进入聊天室</button>
    </div>
</body>

</html>

以下是聊天室的主页面Demo

<!DOCTYPE HTML>
<html>

<head>
    <title>聊天室</title>
    <style>
        .inner {
            max-width: 640px;
            margin: 0 auto;
        }

        h2 {
            text-align: center;
            background: #eee;
            color: red;
            height: 50px;
            line-height: 50px;
        }

        .chat {
            padding: 20px;
            border: 1px solid #f60;
            height: 500px;
        }

        .send {
            width: 100%;
            bottom: 5px;
            height: 44px;
            line-height: 44px;
            display: flex;
            overflow-x: hidden;
        }

        .send input[type='text'] {
            flex: 1;
            margin: 0;
            padding: 0;
            height: 40px;
        }

        #send {
            display: inline-block;
            width: 100px;
            margin: 0;
            padding: 0;
            height: 44px;
        }
    </style>
    <!-- 1.引入服务器上存放的socket.io.js -->
    <script src="http://localhost:8000/socket.io/socket.io.js"></script>
    <script src="jquery-1.11.3.min.js"></script>
    <script>
        $(function () {
            // 2.连接服务器
            var socket = io.connect('http://localhost:8000');

            // 3.将聊天人及消息发送给服务器
            $('#send').click(function () {
                socket.emit('message', {
                    msg: $('#msg').val(),
                    name: '<%=name%>'
                })
            });
            // 4.监听服务器返回的数据
            socket.on('message', function (data) {
                $(".list").append(`<li><strong>${data.name}:</strong> ${data.msg}</li>`);
                $('#msg').val('');
                $('.footer').get(0).scrollIntoView(true);
            });
        })
    </script>
</head>

<body>
    <div class="inner">
        <h2>聊天室</h2>
        <div class="chat" style="overflow-x: auto">
            <ul class="list"></ul>
            <p class="footer"> </p>
        </div>
        <div class="send">
            <input type="text" id="msg" /><button id="send">发送</button>
        </div>
    </div>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/weixin_40629244/article/details/102766760