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

https://github.com/liangshiw/signalrminiprogram-client

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

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

【代码】

  1 const protocal = {
  2   protocol: "json",
  3   version: 1
  4 };
  5 
  6 const messagetype = {
  7   /** indicates the message is an invocation message and implements the {@link invocationmessage} interface. */
  8   invocation: 1,
  9   /** indicates the message is a streamitem message and implements the {@link streamitemmessage} interface. */
 10   streamitem: 2,
 11   /** indicates the message is a completion message and implements the {@link completionmessage} interface. */
 12   completion: 3,
 13   /** indicates the message is a stream invocation message and implements the {@link streaminvocationmessage} interface. */
 14   streaminvocation: 4,
 15   /** indicates the message is a cancel invocation message and implements the {@link cancelinvocationmessage} interface. */
 16   cancelinvocation: 5,
 17   /** indicates the message is a ping message and implements the {@link pingmessage} interface. */
 18   ping: 6,
 19   /** indicates the message is a close message and implements the {@link closemessage} interface. */
 20   close: 7,
 21 }
 22 
 23 
 24 export class hubconnection {
 25 
 26   constructor() {
 27     this.openstatus = false;
 28     this.methods = {};
 29     this.negotiateresponse = {};
 30     this.url = "";
 31     this.invocationid = 0;
 32     this.callbacks = {};
 33   }
 34 
 35   start(url, querystring) {
 36     var negotiateurl = url + "/negotiate";
 37     if (querystring) {
 38       for (var query in querystring) {
 39         negotiateurl += (negotiateurl.indexof("?") < 0 ? "?" : "&") + (`${query}=` + encodeuricomponent(querystring[query]));
 40       }
 41     }
 42     my.request({
 43       url: negotiateurl,
 44       method: "post",
 45       success: (res) => {
 46         this.negotiateresponse = res.data;
 47         this.startsocket(negotiateurl.replace("/negotiate", ""));
 48       },
 49       fail: (res) => {
 50         console.error(`requrst ${url} error : ${res}`);
 51       }
 52     });
 53   }
 54 
 55   startsocket(url) {
 56     url += (url.indexof("?") < 0 ? "?" : "&") + ("id=" + this.negotiateresponse.connectionid);
 57     url = url.replace(/^http/, "ws");
 58     this.url = url;
 59     if (this.openstatus) {
 60       return;
 61     }
 62 
 63     console.log(url);
 64 
 65     my.connectsocket({
 66       url: url
 67     })
 68 
 69     my.onsocketopen(res => {
 70       console.log(`websocket connectioned to ${this.url}`);
 71       this.senddata(protocal);
 72       this.openstatus = true;
 73       this.onopen(res);
 74     });
 75 
 76     my.onsocketclose(res => {
 77       console.log(`websocket disconnection`);
 78       this.openstatus = false;
 79       this.onclose(res);
 80     });
 81 
 82     my.onsocketerror(res => {
 83       console.error(`websocket error msg: ${res}`);
 84       this.close({
 85         reason: res
 86       });
 87       this.onerror(res)
 88     });
 89 
 90     my.onsocketmessage(res => this.receive(res));
 91   }
 92 
 93   on(method, fun) {
 94 
 95     let methodname = method.tolowercase();
 96     if (this.methods[methodname]) {
 97       this.methods[methodname].push(fun);
 98     } else {
 99       this.methods[methodname] = [fun];
100     }
101   }
102 
103   onopen(data) { }
104 
105   onclose(msg) { }
106 
107   onerror(msg) { }
108 
109   close(data) {
110     if (data) {
111       console.error('closed socket: ' + data.reason);
112     }
113 
114     my.closesocket();
115 
116     this.openstatus = false;
117   }
118 
119   senddata(data, success, fail, complete) {
120     my.sendsocketmessage({
121       data: json.stringify(data) + "", //
122       success: success,
123       fail: fail,
124       complete: complete
125     });
126   }
127 
128 
129   receive(data) {
130     if (data.data.length > 3) {
131       data.data = data.data.replace('{}', "")
132     }
133 
134     var messagedatalist = data.data.split("");
135 
136     //循环处理服务端信息
137     for (let servermsg of messagedatalist) {
138       if (servermsg) {
139         var messagedata = servermsg.replace(new regexp("", "gm"), "")
140         var message = json.parse(messagedata);
141 
142         switch (message.type) {
143           case messagetype.invocation:
144             this.invokeclientmethod(message);
145             break;
146           case messagetype.streamitem:
147             break;
148           case messagetype.completion:
149             var callback = this.callbacks[message.invocationid];
150             if (callback != null) {
151               delete this.callbacks[message.invocationid];
152               callback(message);
153             }
154             break;
155           case messagetype.ping:
156             // don't care about pings
157             break;
158           case messagetype.close:
159             console.log("close message received from server.");
160             this.close({
161               reason: "server returned an error on close"
162             });
163             break;
164           default:
165             console.warn("invalid message type: " + message.type);
166         }
167       }
168     }
169   }
170 
171   send(functionname) {
172     var args = [];
173     for (var _i = 1; _i < arguments.length; _i++) {
174       args[_i - 1] = arguments[_i];
175     }
176 
177     this.senddata({
178       target: functionname,
179       arguments: args,
180       type: messagetype.invocation,
181       invocationid: this.invocationid.tostring()
182     });
183     this.invocationid++;
184   }
185 
186   invoke(functionname) {
187     var args = [];
188     for (var _i = 1; _i < arguments.length; _i++) {
189       args[_i - 1] = arguments[_i];
190     }
191 
192     var _this = this;
193     var id = this.invocationid;
194     var p = new promise(function(resolve, reject) {
195 
196       _this.callbacks[id] = function(message) {
197         if (message.error) {
198           reject(new error(message.error));
199         } else {
200           resolve(message.result);
201         }
202       }
203 
204       _this.senddata({
205         target: functionname,
206         arguments: args,
207         type: messagetype.invocation,
208         invocationid: _this.invocationid.tostring()
209       }, null, function(e) {
210         reject(e);
211       });
212 
213     });
214     this.invocationid++;
215     return p;
216   }
217 
218   invokeclientmethod(message) {
219     var methods = this.methods[message.target.tolowercase()];
220     if (methods) {
221       methods.foreach(m => m.apply(this, message.arguments));
222       if (message.invocationid) {
223         // this is not supported in v1. so we return an error to avoid blocking the server waiting for the response.
224         var errormsg = "server requested a response, which is not supported in this version of the client.";
225         console.error(errormsg);
226         this.close({
227           reason: errormsg
228         });
229       }
230     } else {
231       console.warn(`no client method with the name '${message.target}' found.`);
232     }
233   }
234 }

【使用方法】

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