WebSocket实现实时接收消息(前端代码)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/caiyongshengCSDN/article/details/88656587
WebSocket实现实时接收通知,并弹窗提示,以下为前端代码,后端代码自己实现
var init = {
    initWebsocket:function () {
        //判断当前浏览器是否支持WebSocket
        if ('WebSocket' in window) {
            var wsServer = "ws:"+init.getCaption('<%=basePath%>')+"/message/${LOCAL_CLINET_USER.userName}"; 
            //服务器地址,<%=basePath%>为获取jsp本地服务地址,${LOCAL_CLINET_USER.userName}为jeecg后台返回的当前登录的用户名

            websocket = new WebSocket(wsServer);
        }
        else {
            layer.alert('当前浏览器版本过低,请使用指定版本浏览器',{icon: 0})
        }

        //连接发生错误的回调方法
        websocket.onerror = function () {
            console.log('连接失败');
        };

        //连接成功建立的回调方法
        websocket.onopen = function () {
            console.log('连接成功');
            // alert('连接成功',websocket.readyState);//查看websocket当前状态
        }

        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            if(event.data == 1){  //根据后台返回的状态判断是登录还是消息
                layer.alert('您的账号已经在另一处登录了,您被迫下线', {icon: 0},function (index) {
                    layer.close(index);
                    //跳转到登录页
                    window.location.href = 'loginController.do?login'
                });
           }else{
               layer.open({
                     type: 1,
                     title: '消息提醒',
                     shade: false, //遮罩
                     area: ['300px', '150px'],
                     offset: 'rb', //右下角弹出
                     time: 10000, //10秒后自动关闭
                     anim: 2,
                     content: '<div style="margin: 10px">' +
                         '<label style="font-weight: bold">内容:</label>' +
                         '<p style="display:inline-block">'+event.data+'</p>' +
                         '</div>'
                   /*  btn:['确定'],
                     btn1: function (index) {

                     }*/
                 });
            }
        }

        //连接关闭的回调方法
        websocket.onclose = function () {
            console.log('连接断开回调');
        }

        //监听当前页面关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
        window.onbeforeunload = function () {
            init.closeWebSocket();
        }
    },
    //关闭WebSocket连接
    closeWebSocket:function () {
        websocket.close();
    },
    //发送消息
    send:function(message) {
        websocket.send(message);

    },
    //截取符号后面的字符
    getCaption:function(str) {
    var index=str.indexOf("://");
    str = str.substring(index+1,str.length);
    return str;
}
};

猜你喜欢

转载自blog.csdn.net/caiyongshengCSDN/article/details/88656587