Github有一个经过重写的微信小程序SignalR的js类库

https://github.com/liangshiw/SignalRMiniProgram-Client

于是我把他改成支付宝小程序的版本,上面这个项目的核心代码基本没有变,只是小程序开放接口改了一下,在支付宝小程序就能跑起来了

把下面的js代码复制到你的支付宝小程序即可(使用方法在下面):

【代码】

 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.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]));
}
}
my.request({
url: negotiateUrl,
method: "POST",
success: (res) => {
this.negotiateResponse = res.data;
this.startSocket(negotiateUrl.replace("/negotiate", ""));
},
fail: (res) => {
console.error(`requrst ${url} error : ${res}`);
}
});
} startSocket(url) {
url += (url.indexOf("?") < 0 ? "?" : "&") + ("id=" + this.negotiateResponse.connectionId);
url = url.replace(/^http/, "ws");
this.url = url;
if (this.openStatus) {
return;
} console.log(url); my.connectSocket({
url: url
}) my.onSocketOpen(res => {
console.log(`websocket connectioned to ${this.url}`);
this.sendData(protocal);
this.openStatus = true;
this.onOpen(res);
}); my.onSocketClose(res => {
console.log(`websocket disconnection`);
this.openStatus = false;
this.onClose(res);
}); my.onSocketError(res => {
console.error(`websocket error msg: ${res}`);
this.close({
reason: res
});
this.onError(res)
}); my.onSocketMessage(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) {
console.error('closed socket: ' + data.reason);
} my.closeSocket(); this.openStatus = false;
} sendData(data, success, fail, complete) {
my.sendSocketMessage({
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.`);
}
}
}

【使用方法】

const hub = require('../../utils/signalr.js');

const connection = new hub.HubConnection();

//注意:这里的apiHost不是wss或ws,是https或http
connection.start(`${apiHost}/yourHub`, { access_token: '如果有token则填写' }); connection.onOpen = res => {
my.showToast({
content: '成功开启连接'
});
} connection.on('服务器的回调方法', (errorCode) => {
my.showToast({
content: errorCode
});
console.log(errorCode);
}); connection.send('Hub中的方法', '参数1', '参数2');

ASP.NET Core在支付宝小程序中使用signalR的更多相关文章

  1. 支付宝小程序中“<”号写法

    今天遇到一个小问题,记录一下 "<"号在h5页面都是可以直接显示的,但是在运行支付宝小程序时报错,找了一个解决办法 <text> {{char_lt}} 18.5 ...

  2. 支付宝小程序PHP全栈开发--前端样式的设计.acss样式详解

    关于.acss文件 在视频中已经说过了,小程序的设计思想和原生app的设计思想颇为相似,基本的应用单元为页面.当然对于一个页面来说每一个元素的放置位置在哪儿以及显示成什么样子这个是由样式来决定的.我们 ...

  3. 支付宝小程序开发之与微信小程序不同的地方

    前言: 本文仅汇总微信小程序移植支付宝小程序过程中遇到的一些不同的地方,详细请参考官方开发文档. 网络请求: 对于网络请求,基本上改动不大,也就支付宝小程序没有responseType属性及响应码字段 ...

  4. 支付宝小程序与微信小程序开发功能和语法糖不同

    最近开始负责公司webapp数据打通支付宝小程序,之前已经打通了微信小程序,现在根据支付宝小程序的开发文档在之前的模板上面做修改. 在修改模板的过程中,总结一下双方功能和语法糖的不同之处. 框架: a ...

  5. js判断移动端浏览器类型,微信浏览器、支付宝小程序、微信小程序等

    起因 现在市场上各种跨平台开发方案百家争鸣各有千秋,个人认为最成熟的还是hybird方案,简单的说就是写H5各种嵌入,当然作为前端工程师最希望的也就是公司采用hybird方案当作技术路线. 所谓的hy ...

  6. 在Visual Studio 2017中使用Asp.Net Core构建Angular4应用程序

    前言 Visual Studio 2017已经发布了很久了.做为集成了Asp.Net Core 1.1的地表最强IDE工具,越来越受.NET系的开发人员追捧. 随着Google Angular4的发布 ...

  7. 【Asp.Net Core】在Visual Studio 2017中使用Asp.Net Core构建Angular4应用程序

    前言 Visual Studio 2017已经发布了很久了.做为集成了Asp.Net Core 1.1的地表最强IDE工具,越来越受.NET系的开发人员追捧. 随着Google Angular4的发布 ...

  8. 在docker中运行ASP.NET Core Web API应用程序

    本文是一篇指导快速演练的文章,将介绍在docker中运行一个ASP.NET Core Web API应用程序的基本步骤,在介绍的过程中,也会对docker的使用进行一些简单的描述.对于.NET Cor ...

  9. 小程序开发过程中常见问题[微信小程序、支付宝小程序]

    目录 一.样式中如何使用background-image呢? 二.使用自适应单位rpx类似于rem,布局尽量使用flex布局 三.万能的{{双大括号,用于在模版中输出变量 四.你想要的基础组件和API ...

随机推荐

  1. springboot带有进度条的上传

    一.说明 最近要做文件上传,在网上找了很久都没有一个全面的示例,特此记录下来分享给大家. 1.文件上传接口可按照springboot默认实现,也可用commons-fileupload组件,本示例使用 ...

  2. 多维矩阵转一维数组(c++)【转载】

    在由二维矩阵转为一维数组时,我们有两种方式:以列为主和以行为主. 以列为主的二维矩阵转为一维数组时,转换公式为: index=column+row×行数 以行为主的二维矩阵转为一维数组时,转换公式为: ...

  3. Kubernetes Namespaces

    Kubernetes可以使用Namespaces(命名空间)创建多个虚拟集群. 大多数Kubernetes资源(例如pod.services.replication controllers或其他)都在 ...

  4. AnonymousPipeStream的使用案例

    AnonymousPipeStream的使用具体案例如下: 服务端: using System; using System.Data; using System.Data.SQLite; using ...

  5. el-cascader遇到一个坑的问题

    经仔细分析,如果二级和三级的value一样,就会出现这个问题.

  6. 在本地搭建hyperledger fabric 网络

    参考了官方文档,直接就可以了https://hyperledger-fabric.readthedocs.io/en/latest/build_network.html 很好用 ➜ ~ cd $GOP ...

  7. Java 解析XML数据

    实例一:获取指定两个标签之间的数据 XML数据格式: <?xml version="1.0" encoding="utf-8"?> <soap ...

  8. tushare包使用案例

    Tushare是一个免费.开源的python财经数据接口包.主要实现对股票等金融数据从数据采集.清洗加工 到 数据存储的过程,能够为金融分析人员提供快速.整洁.和多样的便于分析的数据,为他们在数据获取 ...

  9. oracle的jdbc 的maven配置

    oracle的jdbc是需要收费,因此在maven的中心库是无法下载.有两个办法引入到工程中,一个是手工,另外一个是加入oracle自己的maven库 一.手工配置(本地依赖) 首先要下载到想要的版本 ...

  10. 一起学习log4cxx

    目前成熟的日志系统有很多,比如log4cxx,log4cpp等,今天一起来学习log4cxx吧,之所以学习这个,首先,这个日志库比较成熟,一直由apach基金在维护,而log4cpp缺乏维护.再者,这 ...