接着上一篇的锅,我们使用Spring+WebSocket+SocketJs方案,兼容处理低版本浏览器不兼容websocket协议的问题;
1.web客户端页面展示推送信息其消息处理页面msg.jsp需引用socket客户端js,引用路径如下:
<%--引用的socket客户端处理封装--%>
<script src="<%=path%>/static/index/socket.js"></script>
<%--引用的socket客户端js--%>
<script src="<%=path%>/static/common/js/sockjs-client_1.1.1_sockjs.min.js"></script>
<%--H5的前端session缓存兼容ie的处理方法--%>
<script src="<%=path%>/static/common/utils/sessionStorage.js"></script>
其中, sockjs-client_1.1.1_sockjs.min.js可以去网站下载;sessionStorage.js主要内容如下:
/**
*补充不支持sessionStorage的浏览器使用cookie代替
*
* */
if (!window.sessionStorage) {
// noinspection JSAnnotator
window.sessionStorage = {
getItem: function (sKey) {
if (!sKey || !this.hasOwnProperty(sKey)) {
return null;
}
return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));
},
key: function (nKeyId) {
return unescape(document.cookie.replace(/\s*\=(?:.(?!;))*$/, "").split(/\s*\=(?:[^;](?!;))*[^;]?;\s*/)[nKeyId]);
},
setItem: function (sKey, sValue) {
if (!sKey) {
return;
}
document.cookie = escape(sKey) + "=" + escape(sValue) + "; path=/";
this.length = document.cookie.match(/\=/g).length;
},
length: 0,
removeItem: function (sKey) {
if (!sKey) {
return;
} else if (!this.hasOwnProperty(sKey)) {
return;
}
document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
this.length--;
},
hasOwnProperty: function (sKey) {
return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
}
};
window.sessionStorage.length = (document.cookie.match(/\=/g) || window.sessionStorage).length;
}
其中,socket.js的主要内容如下:
var ip = window.location.host;
var url = new StringBuffer();
url.append(ip).append(path);
var param = new StringBuffer();
param.append("?userName=").append(userName);
param.append("&loginUserId=").append(loginUserId);
$(function(){
var socket = null;
var target = "ws://"+url+"/webSocketServer"+param;
//权限控制webSocket登录
if(isLogin == "true"){
if('WebSocket' in window) {
socket = new WebSocket(target);
} else if ('MozWebSocket' in window) {
socket = new MozWebSocket(target);
} else {
//兼容低版本浏览器而模拟的socket请求
socket = new SockJS("http://"+url+"/sockjs/webSocketServer"+param);
}
socketEvent();
}
//socketJs的事件与webSocket一致,都支持方法和监听
function socketEvent(){
socket.onopen = function(event) {...};
//获取服务端消息
socket.onmessage = function(event) {
var msg=JSON.parse(event.data);
var type=1;
if(msg.messageType===0){