分享

express+socket.io实现一个简易聊天窗

 精品唯居 2021-09-29

首先是node代码:

const express = require('express')
const bodyParser = require('body-parser')
const app = express()


app.use(bodyParser.urlencoded({ extended: false }))


const server = require('http').createServer(app);

const io = require('socket.io')(server);
// 登陆接口
app.post('/login', (req, res) => {
    console.log(req.body)
    let { name, password } = req.body
    if (name === 'admin') {
        if (password === 'admin') {
            res.json({ code: 200, msg: '验证通过' })
        } else {
            res.json({ code: 500, msg: '密码错误' })
        }
    } else {
        res.json({ code: 500, msg: '用户名错误' })
    }

})



const lsit = ['仁义道德,也是一种奢侈', '时间不在于你拥有多少,而在于你怎样使用', '放马过来吧!你会死的很光荣的', '念当年有爱的我,可惜啊,你们看不到啦',
    '即使一无所有,也要未雨绸缪', '落叶的一生,只是为了归根么', '千军万马一将在,探囊取物有何难', '顺我者昌,逆我者亡,此乃天意', '我可以想去哪就去哪,但是我只想进入你的心里',
    '我宁愿犯错误,也不愿什么都不做', '不要测试你的运气,召唤师', '死亡如风,常伴吾身', '我在时光中穿梭,只为找回曾经美好的时光'
]

// websocket
io.on('connection', (socket) => {
    // 向客户端发送消息
    socket.emit('msg', {
        name: '服务端',
        content: '你好,欢迎使用Socket.io'
    })
    // 向所有客户端发送消息
    io.emit('broadcast',/* */)
    socket.on('msg', (msg) => {
        console.log(lsit[Math.floor(Math.random() * lsit.length)])
        setTimeout(() => {
            socket.emit(msg.type, {
                name: '服务端',
                content: lsit[Math.floor(Math.random() * lsit.length)]
            })
        }, 500)

    })

});

app.use(express.static(`${__dirname}/static`))
app.get('/', function (req, res) {

    res.sendFile(`${__dirname}/index.html`)
})
app.get('*', function (req, res) {
    res.send('Hello World')
})
server.listen(3000)

 

 
 
其次是html:
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
    <title>聊天室</title>

    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim 和 Respond.js 是为了让 IE8 支持 HTML5 元素和媒体查询(media queries)功能 -->
    <!-- 警告:通过 file:// 协议(就是直接将 html 页面拖拽到浏览器中)访问页面时 Respond.js 不起作用 -->
    <!--[if lt IE 9]>
      <script src="https://cdn./npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
      <script src="https://cdn./npm/respond.js@1.4.2/dest/respond.min.js"></script>
    <![endif]-->
</head>

<body>

    <div class="container">
        <h1 style="text-align: center;">express+socket.io聊天室</h1>
        <style>
            #showLog {
                display: block;
            }
        </style>
        <!-- 登陆 -->
        <div class="row" id="showLog">
            <div class="col-md-12">
                <div class="form-group">
                    <label for="userId">账号</label>
                    <!-- admin -->
                    <input type="text" class="form-control" id="userId" value="admin" placeholder="输入账号">
                </div>
                <div class="form-group">
                    <label for="password">密码</label>
                    <!-- admin -->
                    <input type="password" class="form-control" id="password" value="admin" placeholder="输入密码">
                </div>
                <button id="login" class="btn btn-success">登陆</button>
            </div>
        </div>
        <style>
            #showCon {
                display: none;
                height: 650px;
                background: url('img/backgroundimg.jpg') center no-repeat;
                background-size: cover;
                border: 2px solid #ccc;
                border-radius: 10px;
                overflow-y: auto;
            }

            .alert {
                padding: 8px;
            }

            .left {
                text-align: left;
            }

            .right {
                text-align: right;
            }
        </style>
        <!-- 聊天室 -->
        <div class="row" id="showCon">
            <div class="col-md-12">
                <!-- 左侧接收别人消息 -->
                <!-- <div class="left">
                    <p><span class="label label-warning">张三</span></p>
                    <p><span class="alert alert-warning">hajdhjahdajdhajsdhjahdjadhjadhj</span></p>
                </div> -->
                <!-- 右侧自己消息 -->
                <!-- <div class="right">
                    <p><span class="label label-success">张三</span></p>
                    <p><span class="alert alert-success">hajdhjahdajdhajsdhjahdjadhjadhj</span></p>
                </div> -->

            </div>

        </div>
        <div style="display: none;" id="hideTxt">
            <div class="form-group row">
                <label for="cont">输入想要发送的消息</label>
                <textarea class="form-control col-md-12" id="cont"
                    onkeydown="if(event.keyCode==13){event.keyCode=0;event.returnValue=false;}"></textarea>
            </div>
            <button style="float: right;" class="btn btn-success" onclick="btnSend()">发送</button>
        </div>
    </div>
    <!-- 模态提示框 -->
    <div class="modal fade" tabindex="-1" role="dialog" id="myModal">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">×</span></button>
                    <h4 class="modal-title">提示</h4>
                </div>
                <div class="modal-body">
                    <p id="modal"></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->

    <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
    <script src="js/jquery.min.js"></script>
    <!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
    <script src="js/bootstrap.min.js"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        var content = $('#showCon .col-md-12');
        var socket = null;

        // 登陆
        $('#login').click(() => {
            var userId = $('#userId').val()
            var password = $('#password').val()
            if (userId && password) {
                $.ajax({
                    url: 'http://localhost:3000/login',
                    type: 'post',
                    data: {
                        name: userId,
                        password
                    },
                    success(res) {
                        if (res.code === 200) {
                            $('#showLog').hide()
                            $("#showCon,#hideTxt").show()
                            socket = io('ws://localhost:3000');
                            socket.on('connect', function () {
                                console.log('建立连接');
                            });
                            socket.on('msg', function (data) {
                                console.log(data)
                                content.append(`
                            <div class="left">
                                <p><span class="label label-warning">${data.name}</span></p>
                                <p><span class="alert alert-warning">${data.content}</span></p>
                            </div>
                            `)
                                scro()
                            });
                            socket.on('disconnect', function () {
                                console.log('断开连接');
                            });
                        }
                    }
                })

            } else {
                $('#myModal').modal('show')
                $('#modal').text('请输入正确的账号或密码')
            }

        })
        // 发送消息到服务端
        // socket.emit('msg', '哈哈哈啊哈')
        function btnSend() {
            var txt = $('#cont').val()
            if (!txt) {
                $('#myModal').modal('show')
                $('#modal').text('请输入内容')
                return;
            } else {
                socket.emit('msg', {
                    name: 'admin',
                    content: txt,
                    type: 'msg'
                })
                content.append(`
                <div class="right">
                    <p><span class="label label-success">admin</span></p>
                    <p><span class="alert alert-success">${txt}</span></p>
                </div>`
                )
                $('#cont').val('')
                scro()
            }
        }

        // 滚动条已知在底部
        function scro() {
            var scr = document.querySelector('#showCon')
            scr.scrollTop = scr.scrollHeight;
        }

        window.onkeydown = (e) => {
            var theCode = e || window.event
            if (theCode.keyCode === 13) {
                btnSend()
            }
        }
    </script>
</body>

</html>

 

 
然后有一些npm包,我把package.json里面内容拿过来,方便安装依赖
{
  "name": "socketIo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bootstrap": "^3.4.1",
    "express": "^4.17.1",
    "socket.io": "^2.3.0"
  }
}

 

 
 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约