我有一个 MXChip 将数据发送到 Azure IoT 中心,从那里我使用带有 Azure SignalR 绑定的 Azure 函数将设备数据发布到 Azure Signal R。我有一个 Angular 客户端,它将通过调用我创建的 Azure 协商函数使用包@aspnet/signalr
.
但问题是我的 Angular 客户端每隔几秒就会抛出一个错误,当我检查时,我可以理解该hubConnection.onclose
事件每隔几秒就会被触发。
下面是我的 Angular 服务代码。
export class SignalRService {
mxChipData: Subject < string > = new Subject();
private hubConnection: SignalR.HubConnection;
constructor(private http: HttpClient) {}
private getSignalRConnection(): Observable < SignalRConnection > {
return this.http.get < SignalRConnection > (`${environment.baseUrl}negotiate`);
}
init() {
this.getSignalRConnection().subscribe(con => {
const options = {
accessTokenFactory: () => con.accessToken
};
this.hubConnection = new SignalR.HubConnectionBuilder()
.withUrl(con.url, options)
.configureLogging(SignalR.LogLevel.Information)
.build();
this.hubConnection.on('notify', data => {
this.mxChipData.next(data);
});
this.hubConnection.start()
.catch(error => console.error(error));
this.hubConnection.onclose((error) => {
console.error(`Something went wrong: ${error}`);
});
});
}
}
有什么办法可以摆脱这种行为吗?
我想出了一个简单的解决办法。该SignalR.HubConnection
具有的属性serverTimeoutInMilliseconds
和keepAliveIntervalInMilliseconds
。
serverTimeoutInMilliseconds
服务器超时(以毫秒为单位)。
如果此超时时间过去而未收到来自服务器的任何消息,则连接将因错误而终止。默认超时值为 30,000 毫秒(30 秒)。
keepAliveIntervalInMilliseconds
ping 服务器的默认时间间隔。
默认值为 15,000 毫秒(15 秒)。允许服务器检测硬断开连接(例如当客户端拔掉计算机时)。
我只是将这些值设置为更大的数字。
this.hubConnection.serverTimeoutInMilliseconds = 300000;
this.hubConnection.keepAliveIntervalInMilliseconds = 300000;
我们还可以在onclose
事件中再次启动集线器作为临时修复。
this.hubConnection.onclose((error) => {
this.hubConnection.start();
console.error(`Something went wrong: ${error}`);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句