uni app Signalr 支持 微信小程序和支付宝小程序

这篇具有很好参考价值的文章主要介绍了uni app Signalr 支持 微信小程序和支付宝小程序。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

const protocal = {
	protocol: "json",
	version: 1
};

const MessageType = {
	/** Indicates the message is an Invocation message and implements the {@link InvocationMessage} interface. */
	Invocation: 1,
	/** Indicates the message is a StreamItem message and implements the {@link StreamItemMessage} interface. */
	StreamItem: 2,
	/** Indicates the message is a Completion message and implements the {@link CompletionMessage} interface. */
	Completion: 3,
	/** Indicates the message is a Stream Invocation message and implements the {@link StreamInvocationMessage} interface. */
	StreamInvocation: 4,
	/** Indicates the message is a Cancel Invocation message and implements the {@link CancelInvocationMessage} interface. */
	CancelInvocation: 5,
	/** Indicates the message is a Ping message and implements the {@link PingMessage} interface. */
	Ping: 6,
	/** Indicates the message is a Close message and implements the {@link CloseMessage} interface. */
	Close: 7,
}


export class HubConnection {

	constructor() {
		this.openStatus = false;
		this.methods = {};
		this.negotiateResponse = {};
		this.connection = {};
		this.url = "";
		this.invocationId = 0;
		this.callbacks = {};
	}


	start(url, queryString) {
		var negotiateUrl = url + "/negotiate";
		if (queryString) {
			for (var query in queryString) {
				negotiateUrl += (negotiateUrl.indexOf("?") < 0 ? "?" : "&") + (`${query}=` + encodeURIComponent(
					queryString[query]));
			}
		}

		uni.request({
			url: negotiateUrl,
			method: "post",
			async: false,
			success: res => {
				this.negotiateResponse = res.data;
				this.startSocket(negotiateUrl.replace("/negotiate", ""));
			},
			fail: res => {
				console.error(`requrst ${url} error : ${res}`);
				return;
			}
		});

	}

	startSocket(url) {
		url += (url.indexOf("?") < 0 ? "?" : "&") + ("id=" + this.negotiateResponse.connectionId);
		url = url.replace(/^http/, "ws");
		this.url = url;
		if (this.connection != null && this.openStatus) {
			return;
		}

		// #ifdef MP-WEIXIN
		this.connection = wx.connectSocket({
			url: url,
			method: "get"
		})
		console.log("微信 WEIXIN");
		// #endif

		// #ifdef MP-ALIPAY
		this.connection = my.connectSocket({
			url: url,
			method: "get"
		})
		console.log("支付宝 ALIPAY");
		// #endif


		this.connection.onOpen(res => {
			console.log(`websocket connectioned to ${this.url}`);
			this.sendData(protocal);
			this.openStatus = true;
			this.onOpen(res);
		});

		this.connection.onClose(res => {
			console.log(`websocket disconnection`);
			this.connection = null;
			this.openStatus = false;
			this.onClose(res);
		});

		this.connection.onError(res => {
			console.error(`websocket error msg: ${msg}`);
			this.close({
				reason: msg
			});
			this.onError(res)
		});

		this.connection.onMessage(res => this.receive(res));
	}


	on(method, fun) {

		let methodName = method.toLowerCase();
		if (this.methods[methodName]) {
			this.methods[methodName].push(fun);
		} else {
			this.methods[methodName] = [fun];

		}
	}

	onOpen(data) {}

	onClose(msg) {}

	onError(msg) {}


	close(data) {
		if (data) {
			this.connection.close(data);
		} else {
			this.connection.close();
		}

		this.openStatus = false;
	}

	sendData(data, success, fail, complete) {
		this.connection.send({
			data: JSON.stringify(data) + "", //
			success: success,
			fail: fail,
			complete: complete
		});
	}


	receive(data) {
		if (data.data.length > 3) {
			data.data = data.data.replace('{}', "")
		}

		var messageDataList = data.data.split("");

		//循环处理服务端信息
		for (let serverMsg of messageDataList) {
			if (serverMsg) {
				var messageData = serverMsg.replace(new RegExp("", "gm"), "")
				var message = JSON.parse(messageData);

				switch (message.type) {
					case MessageType.Invocation:
						this.invokeClientMethod(message);
						break;
					case MessageType.StreamItem:
						break;
					case MessageType.Completion:
						var callback = this.callbacks[message.invocationId];
						if (callback != null) {
							delete this.callbacks[message.invocationId];
							callback(message);
						}
						break;
					case MessageType.Ping:
						// Don't care about pings
						break;
					case MessageType.Close:
						console.log("Close message received from server.");
						this.close({
							reason: "Server returned an error on close"
						});
						break;
					default:
						console.warn("Invalid message type: " + message.type);
				}
			}
		}
	}


	send(functionName) {

		var args = [];
		for (var _i = 1; _i < arguments.length; _i++) {
			args[_i - 1] = arguments[_i];
		}

		this.sendData({
			target: functionName,
			arguments: args,
			type: MessageType.Invocation,
			invocationId: this.invocationId.toString()
		});
		this.invocationId++;
	}


	invoke(functionName) {
		var args = [];
		for (var _i = 1; _i < arguments.length; _i++) {
			args[_i - 1] = arguments[_i];
		}

		var _this = this;
		var id = this.invocationId;
		var p = new Promise(function(resolve, reject) {

			_this.callbacks[id] = function(message) {
				if (message.error) {
					reject(new Error(message.error));
				} else {
					resolve(message.result);
				}
			}

			_this.sendData({
				target: functionName,
				arguments: args,
				type: MessageType.Invocation,
				invocationId: _this.invocationId.toString()
			}, null, function(e) {
				reject(e);
			});

		});
		this.invocationId++;
		return p;

	}

	invokeClientMethod(message) {
		var methods = this.methods[message.target.toLowerCase()];
		if (methods) {
			methods.forEach(m => m.apply(this, message.arguments));
			if (message.invocationId) {
				// This is not supported in v1. So we return an error to avoid blocking the server waiting for the response.
				var errormsg = "Server requested a response, which is not supported in this version of the client.";
				console.error(errormsg);
				this.close({
					reason: errormsg
				});
			}
		} else {
			console.warn(`No client method with the name '${message.target}' found.`);
		}
	}
}

使用方法文章来源地址https://www.toymoban.com/news/detail-595425.html

			var Hub = require("@/config/Signalr.js")
			let connection = new Hub.HubConnection();
			//注意:这里的apiHost不是wss或ws,是https或http
			connection.start(`https://15826q7q9.oicp.vip/ws`, {
				access_token: '如果有token则填写'
			});

			connection.onOpen = res => {
				uni.showToast({
					content: '成功开启连接'
				});
			}

			connection.on('system', (res) => {
				uni.showToast({
					content: res
				});
				console.log(res);
			});

			connection.on("receive", res => {
				uni.showToast({
					content: '消息' + res.msg
				});

			})

到了这里,关于uni app Signalr 支持 微信小程序和支付宝小程序的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • uni-app使用支付宝小程序开发者工具开发钉钉小程序

    一、添加运行配置 在项目的 package.json 文件中添加以下配置 配置完毕后在 HBuilderX 中会显示运行钉钉小程序按钮  二、设置钉钉小程序开发工具路径(支付宝小程序开发者工具)  三、通过 HBuilderX  把 uniapp 项目编译成钉钉小程序 编译成功后会自动打开钉钉小程序开发工具,编

    2024年02月11日
    浏览(38)
  • 跳转微信小程序和支付宝小程序

    参考链接 获取微信小程序 URL Scheme 1.1 获取小程序连接 这里需要获取长期有效的 Scheme,方式如下: 联系小程序开发者 其他渠道 示例 小程序 Scheme : 测试地址,可以打开小程序,只是打开后显示已注销 weixin://dl/business/?ticket=l92578fd8404e0d4e3e975f910fa43f3a 1.2 跳转使用 苹果手机中

    2024年02月06日
    浏览(57)
  • uniapp兼容微信小程序和支付宝小程序遇到的坑

    改为v-if。 App端和H5端支持 v-html ,微信小程序会被转为 rich-text,其他端不支持 v-html。 解决方法:去插件市场找一个支持跨端的富文本组件。 兼容微信小程序和支付宝小程序  pages.json: 给支付宝的导航栏设置 透明 agent页面: 支付宝加上 my.setNavigationBar 设置标题文字即可,

    2024年02月15日
    浏览(62)
  • 【uniapp】将微信小程序的代码兼容支付宝小程序(持续更新)

    目前本身就有一套完善的微信小程序(兼容h5)的代码,现在的需求是将它编译成支付宝小程序,做好兼容的处理,以便后续接入支付宝服务商,在这里简单记录一下目前发现的把微信小程序编译成支付宝小程序的问题和解决方案。 建议配合其他人的记录一起看,这里只是我

    2024年02月09日
    浏览(104)
  • 【uni-app】只支持在微信小程序运行的 导入外部3d模型

    uniapp 导入3d模型,在微信小程序端运行。只支持在微信小程序端使用,若要支持 h5 和 APP端,可以查看这篇,点击这里 只导入了3d模型,未设置让模型动。 glb 格式 (1)首先文件 下载适配微信小程序的 three.js 地址:https://github.com/wechat-miniprogram/threejs-miniprogram (2)导入文件

    2023年04月08日
    浏览(34)
  • uniapp 之 微信小程序、支付宝小程序 对于自定义导航栏的不同

    目录 前言  微信小程序 代码  支付宝小程序 首页配置文件 二级菜单页面  配置 总结  不同 相同  小程序都是 uni-app 写的 不是原生 pages.json文件中配置 重点: \\\"navigationStyle\\\": \\\"custom\\\",  // 导航栏样式  首页 vue文件 template  script  备注:  height:是胶囊的高度 首页配置文件

    2024年02月15日
    浏览(29)
  • 一码多端,一个二维码适用微信小程序,支付宝小程序,h5页面

    最近公司研发自己的一个小程序,因为是线下树牌,涉及到扫码这个问题,但是扫码又分三个端,浏览器扫码,微信扫一扫,支付宝扫码,做这个需求也是遇到了很多坑,在此记录一下 1.扫码进入微信小程序 首先登录微信公众平台,链接 https://mp.weixin.qq.com/  原本此处会有一

    2024年02月08日
    浏览(51)
  • uniapp 蓝牙连接设备 下发命令 监听蓝牙与设备的连接状态(兼容 微信小程序和支付宝小程序)

    1:创建蓝牙需要调用的Api文件 ly.js 2 在页面中使用index.vue 

    2024年04月14日
    浏览(32)
  • uni-app Vue3实现一个酷炫的多功能音乐播放器支持微信小程序后台播放

    本文存在多张gif演示图,建议在 wifi 环境下阅读📖 最近在做网易云音乐微信小程序开源项目的时候,关于 播放器功能 参考了一些成熟的微信小程序,如 网易云音乐小程序 和 QQ音乐小程序 ,但是发现这些 小程序端 的播放器相对于 APP端 来说较简单,只支持一些基础功能,

    2024年01月24日
    浏览(43)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包