websocket+sockjs+stompjs详解及实例
websocket+sockjs+stompjs详解及实例
https://segmentfault.com/a/1190000017204277
/*** 依赖文件sockjs.js、stomp.js* */;!(function (window) {'use strict'let WS = function () {//保存所有的订阅事件 {Aevent:[pubfun(status,data),pubfun(status,data),...]}this.subEvents = {};this.isConnect = false;this.stompClient = null;this.selfClose = false;this.ws = null;this.url = null;};WS.prototype = {constructor: WS//设置连接状态, setConnect(status) {this.isConnect = status;}//建立连接, connect(url) {//若没有连接,才连接this.isConnect = false;this.url = url;this.ws = new SockJS(url);this.stompClient = Stomp.over(ws);this.stompClient.connect({}, (data) => {this.setConnect(true);this.connectSuc.apply(this, [stompClient, data]);}, (error) => {this.setConnect(false);this.connectErr.apply(this,[stompClient,error]);});this.ws.onclose = (e) => {this.isConnect = false;if(!this.selfClose){this.reConnect();}}return stompClient;}//手动断开连接, disconnect() {if(this.stompClient != null && this.isConnect) {this.stompClient.disconnect();this.isConnect = false;this.selfClose = true;this.ws = null;this.stompClient = null;}}//重连, reConnect(){if(this.isConnect){return;}this.connect(this.url);}//连接成功后的回调, connectSuc(stompClient, data) {if(this.isConnect){//发布连接成功事件this.trigger.apply(this, ['connectSuc', stompClient.subscribe.bind(stompClient), data]);//发布发送消息到服务端事件this.trigger.apply(this, ['sendMessage', stompClient.send.bind(stompClient), data]);}}//连接失败后的回调, connectErr(stompClient, data){//发布连接失败事件this.trigger.apply(this, ['connectErr', stompClient, data]);}//发布函数, trigger(eventType, ...data) {eventType = this.subEvents[eventType];for (var i = 0; i < eventType.length; i++) {eventType[i].apply(this, data);}}//订阅方法 --->用于订阅指定事件, on(eventType, handle) {if (!(eventType in this.subEvents)) {this.subEvents[eventType] = [];}this.subEvents[eventType].push(handle);}//删除订阅, off(eventType, handle) {eventType = this.subEvents[eventType];if (eventType) {let handleIndex = eventType.indexOf(handle);if (handleIndex >= 0) {eventType.splice(handleIndex, 1);}}}};window.WS = WS;})(window);/**** var ws = new WS();ws.connect("/helloWebsocket");ws.on('connectSuc',function (subscribe,data) {subscribe('/topic/serverSend', function(response){info.innerHTML += "<div>"+response+"</div>";});subscribe('/topic/serverResponse',function (response) {info.innerHTML += "<div>"+response+"</div>";});});ws.on('connectErr',function (stompClient,data) {});//客户端发送消息给服务端ws.on('sendMessage',function (send,data) {send("/client/clientSendMessage",{},"hello server !!");});//强制关闭窗口后,断开连接window.onunload = function (ev) {ws.disconnect();}** */
