66 lines
1.5 KiB
Markdown
66 lines
1.5 KiB
Markdown
|
# Lyuan-SignalR
|
||
|
|
||
|
## 使用方法与官方文档一致,请自行参考[官方文档](https://docs.microsoft.com/zh-cn/aspnet/core/signalr/introduction?view=aspnetcore-5.0)
|
||
|
|
||
|
兼容微信小程序、h5、Android、ios ,其他小程序未测, 理论支持。
|
||
|
断线重连、重试等功能需自行判断,该库修改自微软官方。
|
||
|
|
||
|
|
||
|
```javascript
|
||
|
import {
|
||
|
HubConnectionBuilder,
|
||
|
LogLevel
|
||
|
} from './signalr.js';
|
||
|
const connection = new HubConnectionBuilder()
|
||
|
.withUrl("http://xxx.com/messagehub", {
|
||
|
// accessTokenFactory: () => {
|
||
|
// return 'token';
|
||
|
// }
|
||
|
})
|
||
|
.configureLogging(LogLevel.Trace)
|
||
|
.build();
|
||
|
|
||
|
//接收消息
|
||
|
connection.on("ReceiveMessage", function (user, message) {
|
||
|
;
|
||
|
});
|
||
|
|
||
|
//发送消息, 需在链接成功后调用
|
||
|
//connection.invoke('方法名',参数)
|
||
|
|
||
|
//链接断开
|
||
|
connection.on/close(function () { //去掉斜杠
|
||
|
;
|
||
|
//重试
|
||
|
start(ms);
|
||
|
});
|
||
|
|
||
|
const ms = 5000;
|
||
|
const start = (timer) => {
|
||
|
setTimeout(() => {
|
||
|
try {
|
||
|
connection
|
||
|
.start()
|
||
|
.then(() => {
|
||
|
;
|
||
|
})
|
||
|
.catch((e) => {
|
||
|
//重试
|
||
|
// console.log("websocket连接失败", e);
|
||
|
start(ms);
|
||
|
});
|
||
|
} catch (e) {
|
||
|
//重试
|
||
|
start(ms);
|
||
|
}
|
||
|
}, timer);
|
||
|
};
|
||
|
|
||
|
//开始连接
|
||
|
start(0);
|
||
|
|
||
|
```
|
||
|
|
||
|
|
||
|
###觉得有用的话,可直接打赏或微信
|
||
|
<img src='https://vkceyugu.cdn.bspapp.com/VKCEYUGU-aliyun-w83z4an5gxdjff2ce6/1cb1d210-53af-11eb-8ff1-d5dcf8779628.jpg' width='40%' />
|