前端开发nodejs+ws+Websocket创建简单聊天室

前端开发技术课程设计
前端开发技术包括啥
常用的前端开发技术

最近在研究nodejs的时候看到一个使用websocket创建聊天室的栗子,觉得很好玩,打个笔记方便查阅,页面略简陋,不支持发送图片且缺少对用户发送图片表情的处理,有时间再优化

线上版本已发布芒果读书,主页-聊天室,在线体验

html 代码

<!DOCTYPE html>
<html lang=”en”>
    <head>
        <meta charset=”UTF-8″ />
        <title>websocket</title>
        <style>
            .mbox,
            .inputs {
                padding: 20px 40px;
                min-height: 100px;
            }
            input,
            textarea {
                padding: 8px 15px;
                display: block;
                width: 300px;
                margin-bottom: 20px;
            }
        </style>
    </head>
    <body>
        <ul class=”mbox”></ul>
        <div class=”inputs”>
            <input type=”text” class=”name” placeholder=”昵称” />
            <textarea cols=”5″ class=”msg” placeholder=”输入消息”></textarea>
            <button onclick=”sendMsg()”>发送</button>
        </div>
        <script type=”text/javascript”>
            var ws = new WebSocket(‘ws://192.168.120.110:3000’)
            var mbox = $(‘.mbox’)
            ws.onopen = function() {
                mbox.innerHTML = ‘<li>连接状态:’ + ws.readyState + ‘</li>’
            }
            ws.onmessage = function(m) {
                var m = eval(‘(‘ + m.data + ‘)’)
                if (m.code == 200) {
                    var ele = document.createElement(‘li’)
                    switch (m.type) {
                        /*1:系统消息,2:文字消息,3:图片消息*/
                        case 1:
                            ele.innerText = m.name + ‘: ‘ + m.msg
                            break
                        case 2:
                            ele.innerHTML =
                                m.name + ‘: <img src=”‘ + m.msg + ‘”>’
                            break
                    }
                    mbox.appendChild(ele)
                } else {
                    /*失败*/
                }
            }
            function sendMsg() {
                var name = $(‘.name’),
                    msg = $(‘.msg’)
                if (name.value && msg.value) {
                    name.style.display = ‘none’
                } else {
                    return
                }
                var temp = {
                    type: 1,
                    msg: msg.value,
                    name: name.value,
                }
                ws.send(JSON.stringify(temp))
            }
            function $(ele) {
                return document.querySelector(ele)
            }
        </script>
    </body>
</html>

nodejs事例,有想学习研究的小伙伴需要在node环境安装ws模块

javascript 代码

npm install –save ws

javascript 代码

/*
200:请求成功;
*/
var ws = require(‘ws’).Server
var wss = new ws({
    port: 3000,
    verifyClient: socketVerify,
})
function socketVerify(info) {
    /*客户端验证,不验证*/
    return true
}
wss.broadcast = (s, data) => {
    wss.clients.forEach((client) => {
        if (s == 1) {
            data.code = 200
            client.send(JSON.stringify(data))
        } else {
            client.send(
                “{code:200, name:’系统消息’, type:1, msg:'” +
                    data +
                    “退出聊天室’}”,
            )
        }
    })
}
wss.on(‘connection’, function(ws) {
    var count = 0
    wss.clients.forEach(() => {
        count++
    })
    ws.send(
        “{code: 200, name:’系统消息’, type:1, msg:’当前在线” + count + “人。’}”,
    )
    ws.on(‘message’, function(data) {
        var data = eval(‘(‘ + data + ‘)’)
        this.user = data.name
        wss.broadcast(1, data)
    })
    ws.on(‘close’, function() {
        try {
            wss.broadcast(0, this.user)
        } catch (err) {
            /*用户刷新了客户端*/
        }
    })
})
前端开发 新技术
web前端开发技术展望
前端开发技术年度总结
» 本文来自:前端开发者 » 《前端开发nodejs+ws+Websocket创建简单聊天室》
» 本文链接地址:https://www.rokub.com/7921.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
64K

评论 抢沙发

评论前必须登录!