当前位置:   article > 正文

使用webSocket实现及时通信_jwebsocket 怎么保证消息及时传递

jwebsocket 怎么保证消息及时传递

本方案是为了解决前后台及时通信设计的,例如后台代码触发一个事件,可以及时的传递给前台,也就是消息的推送功能.
关于消息的推送,方案1是使用定时任务,Cron表达式设置每分钟处理一下后台逻辑进行事件的判断.方案2是使用webSocket建立消息通信通道,挂起一个线程进行时间的判断和消息推送.虽然都能实现消息推送的功能,但是方案二明显效率更高,对服务器造成的压力相对于方案1来说也更小,这里就简单介绍下使用第二种方案进行消息的及时推送实现方法.
首先说下使用webSocket进行访问是路径格式:ws:// path + “wsMy?jspCode=” + jspCode
以WS开头,后面可以追加参数,上文路径是中的wsMy是为了接下来的过滤器过滤,防止恶意访问.
首先添加webSocket依赖:

<!--spring-websocket-->
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-websocket</artifactId>
          <version>4.0.1.RELEASE</version>
      </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

接下来就是前台页面上的触发访问webSocket:

function getUserId() {
   
    $.ajax({
        type : "post",
        url : "${ctx}/memo/getCurrentUserId",
        beforeSend: function () {
   
            //加载中
            waitload();
        },
        success : function(data) {
   
            currentUserId = data;
            closewait();
            //动态获取当前系统服务器IP地址
            //若执行成功的话,则隐藏进度条提示
            //${ctx}为定义的项目名称,此处不展示,因地制宜
            var path = addrAndPort+"${ctx}/"
            console.log("当前系统的IP及端口号为:"+path);
            var userId = currentUserId;
            if(userId==-1){
                window.location.href="${ctx}/memo/testWebSocket";
            }
            var jspCode = userId;
            var websocket;
            if ('WebSocket' in window) {
                //alert("webSocket"+"ws://" + path + "wsMy?jspCode=" + jspCode);
                <shiro:hasPermission name="user_add_custommenu">
                websocket = new WebSocket("ws://" + path + "wsMy?jspCode=" + jspCode);
                </shiro:hasPermission>
            } else if ('MozWebSocket' in window) {
                websocket = new MozWebSocket("ws://" + path + "wsMy?jspCode=" + jspCode);
            } else {
                websocket = new SockJS("http://" + path + "wsMy/sockjs?jspCode=" + jspCode);
            }
            websocket.onopen = function(event) {
   
                console.log("WebSocket:已连接");
                console.log(event);
            };
            websocket.onmessage = function(event) {
   


                if (event.data =="木有消息啊"){
                    //alert("木有消息啊,测试webSocket是否死亡")
                }else {
                    alert("您有新的提醒,请进入系统首页进行查看")
                    window.flushParent();
                    var  aaa   = event.data.split("*");
                    var id = aaa[0];
                    var content = aaa[1];
                    window.layer.alert(content, {
                         skin: 'layui-layer-molv' //样式类名  自定义样式
                         ,closeBtn: 1    // 是否显示关闭按钮
                         ,anim: 1 //动画类型
                         ,btn: ['取消提醒','确定'] //按钮
                         ,icon: 6    // icon
                        ,yes:function(){
   
                            $.ajax({
                                type : "post",
                                data :{
                                    id :id
                                },
                                url : "${ctx}/memo/cancleNotepadByMap",
                                success : function(data) {
   
                                    window.location.reload();
                                    //若执行成功的话,则隐藏进度条提示
                                    if (data != null && data != 'undefined'
                                        && data == 1) {
                                        layer.msg('该提醒取消成功!', {icon: 6,time:1000});
                                        parent.flushParent();
                                        layer_close();
                                        window.location.reload();
                                    }else if (data == -1) {
                                        layer.msg('记事本名称已经存在!', {icon: 5,time:1000});
                                    }else if (data == 0) {
                                        layer.msg('很抱歉!添加失败!', {icon: 5,time:1000});
                                    }else{
                                        layer.msg('系统异常!请与系统管理员联系!', {icon: 5,time:1000});
                                    }
                                }
                            });
                        }
                        ,btn2:function(){
   
                                 layer.msg('按钮2')
                            }});

                }
            };
            websocket.onerror = function(event) {
   
                console.log("WebSocket:发生错误 ");
                console.log(event);
            };
            websocket.onclose = function(event) {
   
                console.log("WebSocket:已关闭");
                console.log(event);
            }
        }
    })
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106

因为本案例中访问的是当前服务器的路径,所以要对当前服务器的IP以及端口号进行获取,然后赋值给webSocket的访问路径:

/*获取当前用户id*/
var addrAndPort = "";
function getAddrAndport() {
   
    $.ajax({
        type : "get",
        url : "${ctx}/getAddrAndport",
        beforeSend: function () {
   
            //加载中
           
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/717227
推荐阅读
相关标签
  

闽ICP备14008679号