【发布时间】:2020-01-08 03:27:46
【问题描述】:
我正在使用带有 React-native (expo) 前端的 NestJS 后端,并尝试通过 socket.io 库让这两者连接。
我能够从我的服务器向我的移动应用程序发送事件,但由于某种原因无法获得与特定房间关联的事件来触发。
我的移动应用代码:
static socket = socketIOClient(HttpService.socketUrl + '/room', {
transports: ['websocket'],
reconnectionDelay: 1000,
reconnection: true
});
//Called on button click
static joinRoom(roomId) {
console.log('subscribing to room', roomId); //This successfully logs to the console
RoomListener.socket.emit('room-subscription', roomId);
RoomListener.socket.on('room-event', function(data) {
console.log(data); //This never happens!
}
}
和我的后端代码:
@WebSocketGateway(80, { namespace: 'room' })
export class RoomGateway implements OnGatewayConnection {
@WebSocketServer() server: Server;
handleConnection(client: any, ...args: any[]) {
//These successfully log to the console
console.log('connection');
console.log(client.id);
}
@SubscribeMessage('room-subscription')
async joinRoom(
@MessageBody() data: string,
@ConnectedSocket() socket: Socket,
): Promise<string> {
console.log('adding to room ', data); //This successfully logs to the console
socket.join(data);
return data;
}
@SubscribeMessage('roomTest')
roomTest(
@MessageBody() data: string,
@ConnectedSocket() socket: Socket,
): string {
console.log('emitting to room', roomId); //This successfully logs to the console with the proper data
this.server.in(roomId).emit('room-event', 'hello');
return data;
}
}
我也试过this.server.of('/room').in(roomId).emit('room-event', 'hello);
以及this.server.to(...).emit(...) 以及与this.server.sockets 相同的3 个组合。我无法找到关于它们之间区别的明确文档,并且对为什么我无法向我的移动应用发出信号感到困惑。
提前致谢!
【问题讨论】:
标签: react-native socket.io expo nestjs