Reputation: 9
The client and server communicate through sockets. It worked fine at first, but when I started using the socket in another component, I separated the socket into a different file, and suddenly the socket wasn't detecting events.
I thought the parameter or event name was wrong, so I created a temp event and sent it, but it didn't work.
I don't understand why It can't catch the event. I don't know what the situation is, but sometimes the socket detects an event.
This is not a situation where the event cannot be detected because the socket is disconnected first.(handleDisconnect function wasn't called unless client disconnect first)
It is not a situation where the client has not joined the room.(i checked all the room client joined)
⬇️client side(typescript, react)
import { io } from 'socket.io-client';
export const chatSocket = io(`${process.env.REACT_APP_BASE_URL}/chat`, {
auth: { userId: 0 },
});
const HandleChatSocket = () => {
chatSocket.on('connect', () => {
console.log('connected with server');
});
chatSocket.on('temp', (data: number) => {
console.log(data);
});
return null;
};
⬇️server side(nestJs)
@WebSocketGateway({
namespace: 'chat',
cors: {},
})
export class ChatGateway implements OnGatewayConnection, OnGatewayDisconnect {
constructor(private readonly chatService: ChatService) {}
@WebSocketServer()
server: Server;
async handleConnection(client: Socket, ...args: any[]) {
console.log('connected');
const userId = client.handshake.auth.userId; //temp
const rooms = await this.chatService.inquireAllJoinedChatRooms(userId);
rooms.map((room) => client.join(String(room.id)));
}
handleDisconnect(client: any) {
console.log('Method not implemented.');
}
@SubscribeMessage('sendChat')
async sendChat(
client: Socket,
roomId: number
): Promise<void> {
console.log('IMHERE with ');
const userId = client.handshake.auth.userId; //temp
client.to(String(roomId)).emit('temp', userId);
}
}
console.log('IMHERE with '); <- this line was printed well everytime
i want the socket from client that can catch the event from server... 🥹
Upvotes: 0
Views: 183
Reputation: 11
Emitting an event to a room that a socket is in will not automatically send that event back to the client that sent it in the first place (you can imagine why this might be the case). If you want this behaviour (presumably for testing stuff), you have to explicitly send the event back to the client that broadcast it:
client.to(String(roomId)).emit('temp', userId);
client.emit('temp', userId); // Add this line
Upvotes: 0