简介:

stomp.js:uniapp开发的小程序中使用
stomp.js:官网
stomp.js:GitHub

本来使用websocket,后端同事使用了stomp协议,导致前端也需要对应修改。

如何使用

在static/js中新建stomp.js和websocket.js,然后在需要使用的页面引入监听代码+发送代码即可

代码如下:

位置:项目/pages/static/js/stomp.js
1.stomp.js

// Generated by CoffeeScript 1.7.1/*Stomp Over WebSocket http://www.jmesnil.net/stomp-websocket/doc/ | Apache License V2.0Copyright (C) 2010-2013 [Jeff Mesnil](http://jmesnil.net/)Copyright (C) 2012 [FuseSource, Inc.](http://fusesource.com)*/(function() {var Byte, Client, Frame, Stomp,__hasProp = {}.hasOwnProperty,__slice = [].slice;Byte = {LF: '\x0A',NULL: '\x00'};Frame = (function() {var unmarshallSingle;function Frame(command, headers, body) {this.command = command;this.headers = headers != null ? headers : {};this.body = body != null ? body : '';}Frame.prototype.toString = function() {var lines, name, skipContentLength, value, _ref;lines = [this.command];skipContentLength = this.headers['content-length'] === false ? true : false;if (skipContentLength) {delete this.headers['content-length'];}_ref = this.headers;for (name in _ref) {if (!__hasProp.call(_ref, name)) continue;value = _ref[name];lines.push("" + name + ":" + value);}if (this.body && !skipContentLength) {lines.push("content-length:" + (Frame.sizeOfUTF8(this.body)));}lines.push(Byte.LF + this.body);return lines.join(Byte.LF);};Frame.sizeOfUTF8 = function(s) {if (s) {return encodeURI(s).match(/%..|./g).length;} else {return 0;}};unmarshallSingle = function(data) {var body, chr, command, divider, headerLines, headers, i, idx, len, line, start, trim, _i, _j, _len, _ref, _ref1;divider = data.search(RegExp("" + Byte.LF + Byte.LF));headerLines = data.substring(0, divider).split(Byte.LF);command = headerLines.shift();headers = {};trim = function(str) {return str.replace(/^\s+|\s+$/g, '');};_ref = headerLines.reverse();for (_i = 0, _len = _ref.length; _i < _len; _i++) {line = _ref[_i];idx = line.indexOf(':');headers[trim(line.substring(0, idx))] = trim(line.substring(idx + 1));}body = '';start = divider + 2;if (headers['content-length']) {len = parseInt(headers['content-length']);body = ('' + data).substring(start, start + len);} else {chr = null;for (i = _j = start, _ref1 = data.length; start <= _ref1 ? _j < _ref1 : _j > _ref1; i = start <= _ref1 ? ++_j : --_j) {chr = data.charAt(i);if (chr === Byte.NULL) {break;}body += chr;}}return new Frame(command, headers, body);};Frame.unmarshall = function(datas) {var frame, frames, last_frame, r;frames = datas.split(RegExp("" + Byte.NULL + Byte.LF + "*"));r = {frames: [],partial: ''};r.frames = (function() {var _i, _len, _ref, _results;_ref = frames.slice(0, -1);_results = [];for (_i = 0, _len = _ref.length; _i < _len; _i++) {frame = _ref[_i];_results.push(unmarshallSingle(frame));}return _results;})();last_frame = frames.slice(-1)[0];if (last_frame === Byte.LF || (last_frame.search(RegExp("" + Byte.NULL + Byte.LF + "*$"))) !== -1) {r.frames.push(unmarshallSingle(last_frame));} else {r.partial = last_frame;}return r;};Frame.marshall = function(command, headers, body) {var frame;frame = new Frame(command, headers, body);return frame.toString() + Byte.NULL;};return Frame;})();Client = (function() {var now;function Client(ws) {this.ws = ws;this.ws.binaryType = "arraybuffer";this.counter = 0;this.connected = false;this.heartbeat = {outgoing: 10000,incoming: 10000};this.maxWebSocketFrameSize = 16 * 1024;this.subscriptions = {};this.partialData = '';}Client.prototype.debug = function(message) {var _ref;return typeof window !== "undefined" && window !== null ? (_ref = window.console) != null ? _ref.log(message) : void 0 : void 0;};now = function() {if (Date.now) {return Date.now();} else {return new Date().valueOf;}};Client.prototype._transmit = function(command, headers, body) {var out;out = Frame.marshall(command, headers, body);if (typeof this.debug === "function") {this.debug(">>> " + out);}while (true) {if (out.length > this.maxWebSocketFrameSize) {this.ws.send(out.substring(0, this.maxWebSocketFrameSize));out = out.substring(this.maxWebSocketFrameSize);if (typeof this.debug === "function") {this.debug("remaining = " + out.length);}} else {return this.ws.send(out);}}};Client.prototype._setupHeartbeat = function(headers) {var serverIncoming, serverOutgoing, ttl, v, _ref, _ref1;if ((_ref = headers.version) !== Stomp.VERSIONS.V1_1 && _ref !== Stomp.VERSIONS.V1_2) {return;}_ref1 = (function() {var _i, _len, _ref1, _results;_ref1 = headers['heart-beat'].split(",");_results = [];for (_i = 0, _len = _ref1.length; _i < _len; _i++) {v = _ref1[_i];_results.push(parseInt(v));}return _results;})(), serverOutgoing = _ref1[0], serverIncoming = _ref1[1];if (!(this.heartbeat.outgoing === 0 || serverIncoming === 0)) {ttl = Math.max(this.heartbeat.outgoing, serverIncoming);if (typeof this.debug === "function") {this.debug("send PING every " + ttl + "ms");}this.pinger = Stomp.setInterval(ttl, (function(_this) {return function() {_this.ws.send(Byte.LF);return typeof _this.debug === "function" ? _this.debug(">>> PING") : void 0;};})(this));}if (!(this.heartbeat.incoming === 0 || serverOutgoing === 0)) {ttl = Math.max(this.heartbeat.incoming, serverOutgoing);if (typeof this.debug === "function") {this.debug("check PONG every " + ttl + "ms");}return this.ponger = Stomp.setInterval(ttl, (function(_this) {return function() {var delta;delta = now() - _this.serverActivity;if (delta > ttl * 2) {if (typeof _this.debug === "function") {_this.debug("did not receive server activity for the last " + delta + "ms");}return _this.ws.close();}};})(this));}};Client.prototype._parseConnect = function() {var args, connectCallback, errorCallback, headers;args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];headers = {};switch (args.length) {case 2:headers = args[0], connectCallback = args[1];break;case 3:if (args[1] instanceof Function) {headers = args[0], connectCallback = args[1], errorCallback = args[2];} else {headers.login = args[0], headers.passcode = args[1], connectCallback = args[2];}break;case 4:headers.login = args[0], headers.passcode = args[1], connectCallback = args[2], errorCallback = args[3];break;default:headers.login = args[0], headers.passcode = args[1], connectCallback = args[2], errorCallback = args[3], headers.host = args[4];}return [headers, connectCallback, errorCallback];};Client.prototype.connect = function() {var args, errorCallback, headers, out;args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];out = this._parseConnect.apply(this, args);headers = out[0], this.connectCallback = out[1], errorCallback = out[2];if (typeof this.debug === "function") {this.debug("Opening Web Socket...");}this.ws.onmessage = (function(_this) {return function(evt) {var arr, c, client, data, frame, messageID, onreceive, subscription, unmarshalledData, _i, _len, _ref, _results;data = typeof ArrayBuffer !== 'undefined' && evt.data instanceof ArrayBuffer ? (arr = new Uint8Array(evt.data), typeof _this.debug === "function" ? _this.debug("--- got data length: " + arr.length) : void 0, ((function() {var _i, _len, _results;_results = [];for (_i = 0, _len = arr.length; _i < _len; _i++) {c = arr[_i];_results.push(String.fromCharCode(c));}return _results;})()).join('')) : evt.data;_this.serverActivity = now();if (data === Byte.LF) {if (typeof _this.debug === "function") {_this.debug("<<< PONG");}return;}if (typeof _this.debug === "function") {_this.debug("<<< " + data);}unmarshalledData = Frame.unmarshall(_this.partialData + data);_this.partialData = unmarshalledData.partial;_ref = unmarshalledData.frames;_results = [];for (_i = 0, _len = _ref.length; _i < _len; _i++) {frame = _ref[_i];switch (frame.command) {case "CONNECTED":if (typeof _this.debug === "function") {_this.debug("connected to server " + frame.headers.server);}_this.connected = true;_this._setupHeartbeat(frame.headers);_results.push(typeof _this.connectCallback === "function" ? _this.connectCallback(frame) : void 0);break;case "MESSAGE":subscription = frame.headers.subscription;onreceive = _this.subscriptions[subscription] || _this.onreceive;if (onreceive) {client = _this;messageID = frame.headers["message-id"];frame.ack = function(headers) {if (headers == null) {headers = {};}return client.ack(messageID, subscription, headers);};frame.nack = function(headers) {if (headers == null) {headers = {};}return client.nack(messageID, subscription, headers);};_results.push(onreceive(frame));} else {_results.push(typeof _this.debug === "function" ? _this.debug("Unhandled received MESSAGE: " + frame) : void 0);}break;case "RECEIPT":_results.push(typeof _this.onreceipt === "function" ? _this.onreceipt(frame) : void 0);break;case "ERROR":_results.push(typeof errorCallback === "function" ? errorCallback(frame) : void 0);break;default:_results.push(typeof _this.debug === "function" ? _this.debug("Unhandled frame: " + frame) : void 0);}}return _results;};})(this);this.ws.onclose = (function(_this) {return function() {var msg;msg = "Whoops! Lost connection to " + _this.ws.url;if (typeof _this.debug === "function") {_this.debug(msg);}_this._cleanUp();return typeof errorCallback === "function" ? errorCallback(msg) : void 0;};})(this);return this.ws.onopen = (function(_this) {return function() {if (typeof _this.debug === "function") {_this.debug('Web Socket Opened...');}headers["accept-version"] = Stomp.VERSIONS.supportedVersions();headers["heart-beat"] = [_this.heartbeat.outgoing, _this.heartbeat.incoming].join(',');return _this._transmit("CONNECT", headers);};})(this);};Client.prototype.disconnect = function(disconnectCallback, headers) {if (headers == null) {headers = {};}this._transmit("DISCONNECT", headers);this.ws.onclose = null;this.ws.close();this._cleanUp();return typeof disconnectCallback === "function" ? disconnectCallback() : void 0;};Client.prototype._cleanUp = function() {this.connected = false;if (this.pinger) {Stomp.clearInterval(this.pinger);}if (this.ponger) {return Stomp.clearInterval(this.ponger);}};Client.prototype.send = function(destination, headers, body) {if (headers == null) {headers = {};}if (body == null) {body = '';}headers.destination = destination;return this._transmit("SEND", headers, body);};Client.prototype.subscribe = function(destination, callback, headers) {var client;if (headers == null) {headers = {};}if (!headers.id) {headers.id = "sub-" + this.counter++;}headers.destination = destination;this.subscriptions[headers.id] = callback;this._transmit("SUBSCRIBE", headers);client = this;return {id: headers.id,unsubscribe: function() {return client.unsubscribe(headers.id);}};};Client.prototype.unsubscribe = function(id) {delete this.subscriptions[id];return this._transmit("UNSUBSCRIBE", {id: id});};Client.prototype.begin = function(transaction) {var client, txid;txid = transaction || "tx-" + this.counter++;this._transmit("BEGIN", {transaction: txid});client = this;return {id: txid,commit: function() {return client.commit(txid);},abort: function() {return client.abort(txid);}};};Client.prototype.commit = function(transaction) {return this._transmit("COMMIT", {transaction: transaction});};Client.prototype.abort = function(transaction) {return this._transmit("ABORT", {transaction: transaction});};Client.prototype.ack = function(messageID, subscription, headers) {if (headers == null) {headers = {};}headers["message-id"] = messageID;headers.subscription = subscription;return this._transmit("ACK", headers);};Client.prototype.nack = function(messageID, subscription, headers) {if (headers == null) {headers = {};}headers["message-id"] = messageID;headers.subscription = subscription;return this._transmit("NACK", headers);};return Client;})();Stomp = {VERSIONS: {V1_0: '1.0',V1_1: '1.1',V1_2: '1.2',supportedVersions: function() {return '1.1,1.0';}},client: function(url, protocols) {var klass, ws;if (protocols == null) {protocols = ['v10.stomp', 'v11.stomp'];}klass = Stomp.WebSocketClass || WebSocket;ws = new klass(url, protocols);return new Client(ws);},over: function(ws) {return new Client(ws);},Frame: Frame};if (typeof exports !== "undefined" && exports !== null) {exports.Stomp = Stomp;}if (typeof window !== "undefined" && window !== null) {Stomp.setInterval = function(interval, f) {return window.setInterval(f, interval);};Stomp.clearInterval = function(id) {return window.clearInterval(id);};window.Stomp = Stomp;} else if (!exports) {self.Stomp = Stomp;}}).call(this);

位置:项目/pages/static/js/websocket.js
2.websocket.js

const Stomp = require('./stomp.js').Stomp;let socketOpen = false
let socketMsgQueue = []export default {client: null,init(url, header ,connectWS) {if (this.client) {return Promise.resolve(this.client)}return new Promise((resolve, reject) => {const ws = {send: this.sendMessage,onopen: null,onmessage: null}wx.connectSocket({ url, header })wx.onSocketOpen(function (res) {console.log('WebSocket连接已打开!', res)socketOpen = truefor (let i = 0; i < socketMsgQueue.length; i++) {ws.send(socketMsgQueue[i])}socketMsgQueue = []ws.onopen && ws.onopen()})wx.onSocketMessage(function (res) {// ios 缺少 0x00 导致解析失败if (res && res.data) {let value = res.data;let code = value.charCodeAt(value.length - 1);if (code !== 0x00) {value += String.fromCharCode(0x00);res.data = value;}}ws.onmessage && ws.onmessage(res)})wx.onSocketError(function (res) {console.log('WebSocket 错误!', res)})wx.onSocketClose((res) => {this.client = nullsocketOpen = falseconsole.log('WebSocket 已关闭!', res)if(res.code !== 1000){setTimeout(()=>{connectWS()},3000)}})Stomp.setInterval = function (interval, f) {return setInterval(f, interval)}Stomp.clearInterval = function (id) {return clearInterval(id)}const client = (this.client = Stomp.over(ws))// 关闭连接client.close = () =>{wx.closeSocket()}client.connect(header, function () {console.log('stomp connected')resolve(client)})})},sendMessage(message) {if (socketOpen) {wx.sendSocketMessage({data: message,})} else {socketMsgQueue.push(message)}},
}

3.监听+发送代码

import WebSocket from "../../static/js/websocket"
const app = getApp();
data: {objUid: '1',client: null,content: '发送的内容',subscription:''
},
onLoad(options) {// stomp协议请求 this.initWS()
},
onShow() {// 切换任务后台,ws断开后重连if(!WebSocket.client){this.initWS()}
},
onUnload() {// 不关闭websocket连接,但是断开订阅this.data.subscription && this.data.subscription.unsubscribe()// 直接关闭websocket// this.data.client && this.data.client.close()
},
initWS() {WebSocket.init(`${app.globalData.WSURL}/chat`,// 传参{// login: 'admin',// passcode: 'admin',},// ws断开回调() => {this.initWS()}).then((client) => {this.setData({client: client})// 订阅const subscription = client.subscribe(// 路径`/response/${app.globalData.uid}/${this.data.objUid}`,// 接收到的数据(res) => {console.log(res)},// 消息不会被确认接收,不确认每次连接都会推送// { ack: 'client' } )this.setData({subscription: subscription})})
},
// 直接调用发送即可
send() {this.data.client.send(// 路径`/child/${app.globalData.uid}/${this.data.objUid}`,// 自定义参数 http://jmesnil.net/stomp-websocket/doc/{},//priority: 9 // 发送文本JSON.stringify({ 'content': this.data.content }));
},

微信小程序使用stomp.js实现STOMP传输协议的实时聊天相关推荐

  1. 微信小程序首页index.js获取不到app.js中动态设置的globalData的原因以及解决方法

    微信小程序首页index.js获取不到app.js中动态设置的globalData的原因以及解决方法 参考文章: (1)微信小程序首页index.js获取不到app.js中动态设置的globalDat ...

  2. 微信小程序--在app.js 和其他页面中更改globalData的值

    微信小程序--在app.js 和其他页面中更改globalData的值 app.js中修改 其他页面 app.js中修改 在app.js中,应当在小程序初始化完成以后再更改全局变量的值,即在onLau ...

  3. 微信小程序如何通过js操作wxmll的wxss属性

    微信小程序如何通过js操作html的css属性 在web端.手机端.webApp中可以通过js获取dom的方式设置dom属性. 微信小程序中,不能通过这种方式进行操作. 如何在微信小程序中在wxml中 ...

  4. 微信小程序实现通过js操作wxml的wxss属性示例

    微信小程序实现通过js操作wxml的wxss属性示例 前言 实现思路 实现代码 前言 在web端.手机端.webApp中可以通过js获取dom的方式设置dom属性. 微信小程序中,不能通过这种方式进行 ...

  5. 微信小程序获取app.js中的公共数据

    微信小程序获取app.js中的公共数据 小程序项目结构如下 app.js App({list: [{id: 1,name: '完美型',content: "属于第一型的你,相信常常这感觉,对 ...

  6. 微信小程序接入腾讯云IM即时通讯(获取聊天历史记录开发步骤)

    微信小程序接入腾讯云IM即时通讯(获取聊天历史记录开发步骤) 1.先看文档: 获取 C2C 历史消息 :https://cloud.tencent.com/document/product/269/1 ...

  7. uniapp 微信小程序打包 vendor.js过大 导致打包超过2M

    1.分包加载,小程序限制一个包2M,可以分9个子包,整包共计不能超出20M,这一步很简单,如果看文档感觉枯燥的可以参考uview框架的demo,因为这个demo就使用了小程序的分包机制,demo链接( ...

  8. 微信小程序 引用其他js里的方法

    微信小程序中,在微信官方开发文档我们可以知道 小程序的目录结构 . 一个小程序页面由四个文件组成,一个小程序页面的四个文件具有相同路径与文件名,由此我们可知一个小程序页面对应着一个跟页面同名的js文件 ...

  9. 微信小程序使用crypto.js加密解密

    微信小程序中使用crypto.js crypto.js是用来进行AES加密的 注意AES在使用时有7个配置项,前后端加解密记着统一参数,测试时注意配置项的选择是否一致. 测试工具: AES加密测试工具 ...

  10. style 对象 微信小程序_微信小程序中一些JS常识

    1.小程序中不支持HTTP请求,配置后台服务器域名只支持https(假设配置后,运行程序还是报域名配置问题,重启开发工具即可),图片地址可以用http. 2.支持请求网页,但是必须在微信公众平台小程序 ...

最新文章

  1. 20172311『Java程序设计』课程 结对编程练习_四则运算第一周阶段总结
  2. RT-Thread使用ENV生成工程时自己添加的文件被清掉的解决方法
  3. linux 对于Vim配置的方法
  4. deep deepfm wide 区别_个性化推荐如何满足用户口味?微信看一看的技术这样做
  5. iOS开发 - 在状态栏显示FPS,CPU和内存信息
  6. [ZPG TEST 115] 字符串【归类思想】
  7. (day 52 - 约舍夫环问题 ) 剑指 Offer 62. 圆圈中最后剩下的数字
  8. NGN学习笔记8——NGN的安全问题
  9. HeidiSQL使用教程
  10. 高斯牛顿迭代法的原理及实现(经典例子,附C和C++代码,含运行结果)
  11. Win10系统怎么映射网络驱动器?
  12. Douphp cms通杀漏洞(小宇特详解)
  13. Unity经验分享——如何实现黑洞吸附效果
  14. 如何利用Excel将文字颠倒顺序显示
  15. 二元隐函数求二阶偏导_多元函数隐函数微分 二阶偏导的求法
  16. SVN上传的时候没法显示文件名,只显示后缀名
  17. Android中高级进阶开发面试题冲刺合集(七)
  18. transformers之中mt5和t5的区别
  19. request.querystring php,ASP_ASP读取Request.QueryString编码的函数代码,1. 支持参数纯汉字 ?a=深山老熊 - phpStudy...
  20. 数学的故事之“共轭”

热门文章

  1. 中职计算机专业第一年开什么课程,中职学校计算机专业课程教学(共2359字).doc...
  2. 一篇教你学会Ansible
  3. 【赞】深圳华强北的专业乞丐
  4. 腾讯研究院发布《中美两国人工智能产业发展全面解读》:中国AI产业将迎来泡沫?(附全文PDF下载)...
  5. c语言对变量作强制定义理由,C语言中要求对变量作强制定义的主要理由是()。...
  6. 我们要守护的,不止湿地
  7. (算法提高课)图论-单源最短路径问题3
  8. Power BI 一叶霸屏_自我介绍
  9. 人工智能白热化,运维脱帽“背锅侠”|CNUTCon
  10. 一名开发三年的Java程序员陈述:进大公司拿30K+到底有多难?