堆栈是 atm VueJS
,React Native
using Expo
, 和NestJS
用于后端。为方便起见,此 repo包含 VueJS 和 NestJS 部分的工作示例。来自 React Native 端(简化版)的连接是这样实现的:
export const useSubscribeToWebsocket = (token: string) => {
const { socketUrl } = usePlatform()
useEffect(() => {
console.log('open')
const socket = io(socketUrl)
socket.on('connect', () => {
console.log('connect')
socket.send(JSON.stringify(authenticate(token)))
})
socket.on('error', (error: any) => {
dlog('error connection=> ', error)
})
socket.on('event', (socketEvent: any) => {
console.log('event ', socketEvent)
})
return () => {
socket.close()
}
}, [token])
return null
}
网关(套接字服务器)看起来很简单:
@WebSocketGateway()
export class AppGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
@WebSocketServer() server: Server;
private logger: Logger = new Logger('AppGateway');
@SubscribeMessage('msgToServer')
handleMessage(client: Socket, payload: string): void {
this.server.emit('msgToClient', payload);
}
afterInit(server: Server) {
this.logger.log('Init');
}
handleDisconnect(client: Socket) {
this.logger.log(`Client disconnected: ${client.id}`);
}
handleConnection(client: Socket, ...args: any[]) {
this.logger.log(`Client connected: ${client.id}`);
}
}
问题是,虽然移动客户端只连接一次(useEffect
钩子被称为一次,除 之外没有其他日志open
),但handleConnection
会保持连接不同 id 的客户端。connect
也从未在 RN 端登录,所以我想它永远不会连接。我用 VueJS 客户端对其进行了测试,它只连接一次(在后端也可以正常工作),一切正常。
仅与模拟器有关的问题吗?有没有办法解决它?