• 前后端如何保持长连接?---websocket


    1. pc端的应用,一般会采用前端定时请求后台;

    2. app定时去访问后台的话,对用户来说并不友好,会消耗大量的流量,移动端最好的方式就是后台主动向app推送信息;

    3. H5提供了一种比较好的方式是websocket,打开app后,向后台发出请求,后台响应后,就可以实时向前端推送信息了,而无需app再次去访问;

    4.websocket的前端实现方法:

    websocket = null;  
    url="127.xxxxxxx/xxx"  
    var websocketAddress = 'ws://'+ url  ;
    //判断当前浏览器是否支持WebSocket  
    if('WebSocket' in window){  
        websocket new WebSocket(websocketAddress);  
    }  
    else{  
        alert('当前浏览器不支持WebSocket')  
    }  
    //连接发生错误的回调方法  
    websocket.onerror = function(){  
        //notificationReminder("错误");  
    };  
      
    //连接成功时的回调方法  
    websocket.onopen = function(event){  
        console.log(event);  
    }  
      
    //接收到消息的回调方法  
    websocket.onmessage = function(event){  
        $scope.notificationReminder(event.data);  
    }  
      
    //连接关闭的回调方法  
    websocket.onclose = function(){  
        //notificationReminder("关闭");  
    }  
    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。  
    window.onbeforeunload = function(){  
        websocket.close();  
    }  
      
    //发送消息  
    $scope.send = function(){  
        websocket.send(localStorageService.get('UserID'));  
    }  
    $scope.closeWebSocket function(){  
        websocket.close();  
    }  
  • 相关阅读:
    正则表达式
    公司培训文档混淆的基本概念
    堆和栈的区别[导入]
    一個textlist控件(左右兩個文本框)。
    深入浅出之正则表达式(一)
    公司培训文档-c#基础学习
    问题
    [转]CStdioFile中文问题
    VB用户控件制作讲解与实例用户控件属性或函数的描述信息如何写入程序
    什么是表驱动
  • 原文地址:https://www.cnblogs.com/liaolei1/p/7477400.html
Copyright © 2020-2023  润新知