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');

最新文章

  1. 织梦Dedecms使用Nginx的安全设置
  2. 程序员的修养 -- 如何写日志(logging)
  3. yii2 输出xml格式数据
  4. linux 添加用户、权限
  5. eclipse服务器add and remove 工程时出现there are no resources that can be added or removed from the server
  6. java抽象类的使用
  7. redis pool config的配置参数
  8. 学习android的博客
  9. Java执行groovy脚本
  10. 视频-某hadoop高级应用-搜索提示
  11. axf、elf文件转换成bin、hex脚本工具
  12. 解决servlet乱码问题
  13. Scrapy研究和探索(七)——如何防止被ban大集合策略
  14. 初识 BFC、 IFC、GFC、FFC
  15. phpstorm及webstorm密钥
  16. 设计模式之Factory工厂模式的好处
  17. 【学亮IT手记】Java 8新特性实例介绍
  18. Python面试题练习
  19. 【iCore4 双核心板_FPGA】实验十九:使用JTAT UART终端打印信息
  20. WordPress主题开发:更换后台编辑器

热门文章

  1. centos6 启动docker报错
  2. mysql 存储过程 动态表名
  3. python 操作 elasticsearch-7.0.2 遇到的问题
  4. CS224n学习笔记(三)
  5. python ocr图片中汉字识别
  6. uniapp - 键盘弹起背景图片不会被挤压
  7. 常见的SQL优化面试题
  8. 解决Ubuntu系统“无法修正错误,因为您要求某些软件包保持现状,就是它们破坏了软件包间的依赖关系”的有效方法
  9. Xamarin图表开发基础教程(11)OxyPlot框架支持的图表类型
  10. Leetcode: Split BST