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

简介:

uniapp开发的小程序中使用
本来使用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) {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.connect(header, function () {console.log('stomp connected')resolve(client)})// 关闭连接client.close = () =>{wx.closeSocket()}})},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: '发送的内容'
},
onLoad(options) {// stomp协议请求 this.initWS()
},
onUnload() {this.client && this.client.close()
},
initWS() {WebSocket.init(`${app.globalData.WSURL}/chat`,// 传参{// login: 'admin',// passcode: 'admin',},// ws断开回调() => {this.initWS()}).then((client) => {this.setData({client: client})// 订阅client.subscribe(// 路径`/response/${app.globalData.uid}/${this.data.objUid}`,// 接收到的数据(res) => {console.log(res)},// 消息不会被确认接收,不确认每次连接都会推送// { ack: 'client' } )})
},
// 直接调用发送即可
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 }));
},

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/62729.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【rust/egui】(五)看看template的app.rs:SidePanel、CentralPanel以及heading

说在前面 rust新手&#xff0c;egui没啥找到啥教程&#xff0c;这里自己记录下学习过程环境&#xff1a;windows11 22H2rust版本&#xff1a;rustc 1.71.1egui版本&#xff1a;0.22.0eframe版本&#xff1a;0.22.0上一篇&#xff1a;这里 SidePanel 侧边栏&#xff0c;如下图 …

如何把pdf文件合并?分享最新pdf合并方法

在所有文档格式中&#xff0c;pdf应该是最常用的&#xff0c;像产品介绍、商务合同、法律文书等等&#xff0c;这些都是pdf格式的。有时候出于工作需要&#xff0c;我们要把两份或者多份pdf文件合并在一起&#xff0c;那么问题来了&#xff0c;如何把pdf文件合并呢?小编最近发…

Ubuntu 18.04上无法播放MP4格式视频解决办法

ubuntu18.04系统无法播放MP4格式视频&#xff0c;提示如下图所示&#xff1a; 解决办法&#xff1a; 1、首先&#xff0c;确保ubuntu系统已完全更新。可使用以下命令更新软件包列表&#xff1a;sudo apt update&#xff0c;然后使用以下命令升级所有已安装的软件包&#xff1a…

CDL基础原理

一、CDL简介 CDL&#xff08;全称Change Data Loader&#xff09;是一个基于Kafka Connect框架的实时数据集成服务。 CDL服务能够从各种OLTP数据库中捕获数据库的Data Change事件&#xff0c;并推送到kafka&#xff0c;再由sink connector推送到大数据生态系统中。 CDL目前支…

最新文献怎么找|学术最新前沿文献哪里找

查找下载最新文献最好、最快、最省事的方法就是去收录该文献的官方数据库中下载。举例说明&#xff1a; 有位同学求助下载一篇2023年新文献&#xff0c;只有DOI号10.1038/s41586-023-06281-4&#xff0c;遇到这种情况可以在DOI号前加上http://doi.org/输入地址栏查询该文献的篇…

NetMarvel机器学习促广告收益最大化,加速获客

游戏出海的竞争日益激烈&#xff0c;这并非空穴来风。 从2021年第一季度至2022年第四季度&#xff0c;iOS平台的CPI增长了88%&#xff0c;意味着厂商需要花费近两倍的钱才能获取一个新用户。与此同时数据隐私政策持续收紧&#xff0c;更加提高了营销成本。 在成本高涨的当下&…

基于PIC单片机温度-脉搏-DS18B20温度-液晶12864显示(proteus仿真+源程序)

一、系统方案 1、上电初始化液晶第一行显示脉搏&#xff0c;第二行显示温度&#xff0c;第三行显示模式&#xff0c;第四行显示强度&#xff1b;按下K1按键可以选择模式&#xff0c;催眼模式或治疗模式。 2、治疗模块下&#xff0c;可以通过K2、K3修改强度。 二、硬件设计 原理…

Java 多线程系列Ⅱ(线程安全)

线程安全 一、线程不安全线程不安全的原因&#xff1a; 二、线程不安全案例与解决方案1、修改共享资源synchronized 使用synchronized 特性 2、内存可见性Java内存模型&#xff08;JMM&#xff09;内存可见性问题 3、指令重排列4、synchronized 和 volatile5、拓展知识&#xf…

【网络安全带你练爬虫-100练】第17练:分割字符串

目录 一、目标1&#xff1a;使用函数分割 二、目标2&#xff1a;使用函数模块 三、目标3&#xff1a;使用正则匹配 一、目标1&#xff1a;使用函数分割 目标&#xff1a;x.x.x.x[中国北京 xx云] 方法&#xff1a;split函数replace函数 1、分割&#xff1a;使用split()方法将…

iPhone 15预售:获取关键信息

既然苹果公司将于9月12日正式举办iPhone 15发布会,我们了解所有新机型只是时间问题。如果你是苹果的狂热粉丝,或者只是一个早期用户,那么活动结束后,你会想把所有的注意力都集中在iPhone 15的预购上——这样你就可以保证自己在发布日会有一款机型。 有很多理由对今年的iPh…

聊天平台Revolt的搭建

经网友 凌尘 提醒&#xff0c;Web-Check 最新的镜像版本&#xff0c;容器端口已经从 8888 改为了 3000&#xff0c;特此更正&#xff01; 什么是 Revolt &#xff1f; Revolt 是一个开源的用户至上的聊天平台。是在不牺牲任何可用性的情况下与朋友和社区保持联系的最佳方式之一…

从零学算法(剑指 Offer 36)

123.输入一棵二叉搜索树&#xff0c;将该二叉搜索树转换成一个排序的循环双向链表。要求不能创建任何新的节点&#xff0c;只能调整树中节点指针的指向。 为了让您更好地理解问题&#xff0c;以下面的二叉搜索树为例&#xff1a; 我们希望将这个二叉搜索树转化为双向循环链表。…

pxe网络装机

目录 PXE是什么&#xff1f; PXE的组件&#xff1a; 配置vsftpd关闭防火墙与selinux ​编辑配置tftp 准备pxelinx.0文件、引导文件、内核文件 ​编辑配置dhcp 创建default文件 创建新虚拟机等待安装&#xff08;交互式安装完毕&#xff09; 创建客户端验证&#xff08;…

完整开发实现公众号主动消息推送,精彩内容即刻到达

&#x1f3c6;作者简介&#xff0c;黑夜开发者&#xff0c;CSDN领军人物&#xff0c;全栈领域优质创作者✌&#xff0c;CSDN博客专家&#xff0c;阿里云社区专家博主&#xff0c;2023年6月CSDN上海赛道top4。 &#x1f3c6;数年电商行业从业经验&#xff0c;历任核心研发工程师…

使用 zipfile创建文件压缩工具

在本篇博客中&#xff0c;我们将使用 wxPython 模块创建一个简单的文件压缩工具。该工具具有图形用户界面&#xff08;GUI&#xff09;&#xff0c;可以选择源文件夹中的文件&#xff0c;将其压缩为 ZIP 文件&#xff0c;并将压缩文件保存到目标文件夹中。 C:\pythoncode\new\z…

python基础之miniConda管理器

一、介绍 MiniConda 是一个轻量级的 Conda 版本&#xff0c;它是 Conda 的精简版&#xff0c;专注于提供基本的环境管理功能。Conda 是一个流行的开源包管理系统和环境管理器&#xff0c;用于在不同的操作系统上安装、管理和运行软件包。 与完整版的 Anaconda 相比&#xff0c…

【力扣每日一题】2023.8.31 一个图中连通三元组的最小度数

目录 题目&#xff1a; 示例&#xff1a; 分析&#xff1a; 代码&#xff1a; 题目&#xff1a; 示例&#xff1a; 分析&#xff1a; 题目给我们一个无向图&#xff0c;要我们找出三个节点&#xff0c;这三个节点他们两两相连&#xff0c;这三个节点除了连接到对方的其他线…

【重要】Nand Flash基础知识与坏块管理机制的介绍

概述 Flash名称的由来&#xff0c;Flash的擦除操作是以block块为单位的&#xff0c;与此相对应的是其他很多存储设备&#xff0c;是以bit位为最小读取/写入的单位&#xff0c;Flash是一次性地擦除整个块&#xff1a;在发送一个擦除命令后&#xff0c;一次性地将一个block&…

vue之若依分页组件的导入使用(不直接使用若依框架,只使用若依分页组件)

vue之若依分页组件的导入使用 步骤 步骤&#xff1a; 工具类&#xff1a;src/utils/scroll-to.js 样式&#xff1a;src/assets/styles/ruoyi.scss 组件&#xff1a;src/components/Pagination 全局挂载&#xff1a;src/main.js 复制工具类 复制若依框架中的src/utils/scrol…

Shell编程之函数

目录 基本概念 自定义函数 系统函数 1.read 2.basename 3.dirname 基本概念 将一段代码组合封装在一起实现某个特定的功能或返回某个特定的值&#xff0c;然后给这段代码取个名字&#xff0c;也就是函数名&#xff0c;在需要实现某个特定功能的时候直接调用函数名即可。 函…