前后端如何保持长连接?---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();  
}  
原文地址:https://www.cnblogs.com/liaolei1/p/7477400.html