我正在使用带有角度和套接字 IO 的 Ionic 应用程序(我也在使用 ngrx),但是我遇到了一个问题,即当屏幕处于非活动状态时套接字会停止。
失败过程是这样的:
- 首先您进入应用程序,因此套接字连接。只有当我的 redux 状态有令牌时,套接字才会连接,在其他情况下,套接字将不必连接
- 然后,假设您让应用程序处于执行状态并且您的手机自动锁定屏幕,因此应用程序变为“暂停”状态
- 在暂停状态 10 分钟后,您解锁手机,这会导致应用程序进入恢复状态,然后当套接字使整个应用程序崩溃并且它只是关闭时
插座正常工作
我知道是套接字,因为我尝试只删除我的套接字服务的一些行并且应用程序没有关闭。如果我只需等待 7 或 8 或 5 分钟或更短的时间来解锁手机,应用程序就不会崩溃。崩溃仅在屏幕锁定 10 分钟后发生
这是我的 ngx-socket-io 配置
const config: SocketIoConfig = { url: 'http://localhost:5000', options: { transports: ["websocket", "xhr-polling", "jsonp-polling"], autoConnect: false } };
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
BrowserModule,
HttpClientModule,
IonicModule.forRoot(),
AppRoutingModule,
StoreModule.forRoot(appReducers),
StoreDevtoolsModule.instrument({ maxAge: 25, logOnly: environment.production}),
EffectsModule.forRoot(effectsArray),
SocketIoModule.forRoot(config),
],
providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy } ],
bootstrap: [AppComponent],
})
export class AppModule {}
这是我的 app.component.ts
constructor(public store: Store<AppState>, public websocketService: WebsocketService, public appStatusService: AppStatusService, public platform: Platform) { }
ngOnInit() {
this.store.select('session').pipe(filter(session => session !== null)).subscribe(session => {
// IF I REMOVE THIS CONDITION, THE APP WON'T CRASH
if (session.currentSession.token === null) {
// DISCONNECT IF WAS CONNECTED
this.websocketService.disconnectSocket();
} else {
// CONNECT
this.websocketService.connectSocket();
}
});
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
this.platform.pause.subscribe(e => { this.appStatusService.setStatus(false); });
this.platform.resume.subscribe(e => { this.appStatusService.setStatus(true); });
});
}
这是我的 webSocket 服务
export class WebsocketService {
socketConnected = false;
socketStatus:boolean;
constructor(private socket: Socket, public http: HttpClient, public apiConfigService: ApiConfigService, public authService: AuthService, public platform: Platform) {
this.checkStatus();
}
async connectSocket() {
const data = await this.socketCredentials();
if (data !== null && data !== undefined) {
this.socket.ioSocket.io.opts.query = { sessionUUID: data.sessionUUID, channelUUID: data.channelUUID } ;
this.socketConnected = true;
this.socket.connect();
this.socket.emit( 'JOIN_ROOM', {channelID: data.channelUUID } );
}
}
disconnectSocket() {
if (this.socketConnected === true) { this.socket.disconnect(); this.socketConnected = false; }
}
checkStatus() {
this.socket.on('connect', () => { console.log('SOCKET CONNECTED'); });
this.socket.on('disconnect', () => { console.log('SOCKET DISCONNECTED'); });
}
socketCredentials(): Promise<any> {
// I need to get some credentials to connect the socket. Only can connect to my server if I have this credentials
return new Promise(resolve => {
this.http.get('http://localhost:3000/socket/auth').toPromise().then(response => { resolve(response); });
});
}
}