基于 ThinkJS 的简单聊天室实现

1874次阅读  |  发布于5年以前

thinkjs内置了对websocket的支持,所以要实现聊天室的话非常简单。

Controller里代码

module.exports = Controller(function(){
        //websocket列表
        var wsList = {};
        setInterval(function(){
            for(var id in wsList){
                wsList[id].send({
                    name: "机器人",
                    text: "每隔10秒我就发一条消息哦"
                })
            }
        }, 10000)
        return {
            indexAction: function(){
                this.display();
            },
            /**
             * 建立连接
             * @return {[type]} [description]
             */
            openAction: function(){
                var websocket = this.http.websocket;
                var id = websocket.id;
                for(var wid in wsList){
                    wsList[wid].send({
                        name: "系统",
                        text: "id_" + id + "进入了聊天室"
                    });
                }
                wsList[id] = websocket;
                this.http.on("websocket.close", function(){
                    console.log("close")
                    delete wsList[id];
                    for(var wid in wsList){
                        wsList[wid].send({
                            name: "id_" + id,
                            text: "goodbye~~"
                        });
                    }
                })
            },
            /**
             * 获取到消息
             * @return {[type]} [description]
             */
            messageAction: function(){
                var data = this.get();
                data.name = "id_" + this.http.websocket.id;
                data.wslength = Object.keys(wsList).length;
                //有消息后向所有人广播
                for(var id in wsList){
                    wsList[id].send(data);
                }
            }
        }
    })

浏览器中的代码

$(function(){
        var htmlMaps = {
        "<": "<",
        ">": ">",
        """: ""e;",
        """: """
      }
      var escape_html = function (str) {
        return (str + "").replace(/[<>""]/g, function(a){
          return htmlMaps[a];
        })
      }
        function getWebSocket(){
            var socket = new WebSocket("ws://" + location.hostname + ":1234/test/websocket/open");
            var deferred = $.Deferred();
            // 打开Socket 
            socket.onopen = function(event) {
                    $("<div class="alert alert-success">连接成功,开始聊天吧 ^_^</div>").appendTo(dataList);
                    deferred.resolve(socket);
                // 监听消息
                socket.onmessage = function(event) {
                    var data = JSON.parse(event.data).result;
              console.log(data);
                    var html = "<div class="data-item"><span class="label label-primary">"+data.name+"</span> "
                    html += "<span>" + escape_html(data.text) + "</span></div>"
                    $(html).appendTo(dataList);
                    dataList[0].scrollTop = 100000000;
                }; 
                // 监听Socket的关闭
                socket.onclose = function(event) { 
                    socket = null;
                    console.log("websocket closed")
                };
            };
            return deferred;
        }
        var ws = getWebSocket();
        var dataList = $(".data-list");
        var input = $("#textField").select();
        $("#submitBtn").click(function(){
            var value = input.val().trim();
            if (!value) {
                return input.focus();
            };
            ws.then(function(ws){
                input.val("").focus();
                ws.send(JSON.stringify({
                    jsonrpc: "2.0",
                    method: "/test/websocket/message",
                    params: {text: value},
                    id: 1
                }))
            })
        })
    })

DEMO

具体示例可以看这里

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8