使用 Socket.on 在客户端监听不起作用
当我尝试使用 socket.to(roomId).emit('msgToClient', data)
将其发送到特定房间 ID 时,我的客户端在反应时不监听任何消息,但如果我使用 socket.emit('msgToClient', data) 工作正常,我在下面添加我的客户端和服务器端代码。
在React客户端中使用Chat钩子接收服务器消息message.NestJs
const useChat = (roomId) => {
const [messages, setMessages] = useState([]); // Sent and received messages
const socketRef = useRef();
useEffect(() => {
// Creates a WebSocket connection
socketRef.current = io(SOCKET_SERVER_URL, {
query: { roomId }, transports: ['websocket'] });
// Listens for incoming messages
socketRef.current.on('msgToClient', (message) => {
const incomingMessage = {
...message,
ownedByCurrentUser: message.senderId === socketRef.current.id,
};
setMessages((messages) => [...messages, incomingMessage]);
});
// Destroys the socket reference
// when the connection is closed
return () => {
socketRef.current.disconnect();
};
}, [roomId]);
return { messages, sendMessage, joinRoom };
};
export default useChat;
中的gateway将其发送到客户端
@WebSocketGateway()
export class MessageGateway
implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
@WebSocketServer() socket: Socket;
private logger: Logger = new Logger('MessageGateway');
@SubscribeMessage('msgToServer')
public handleMessage(client: Socket, payload: any): void {
this.socket.to(client.handshake.query.roomId).emit('msgToClient', payload);
}
}
when I am trying to send it to particular room id using socket.to(roomId).emit('msgToClient', data)
my client side on react not listening any messages but if I use socket.emit('msgToClient', data)
its working fine, I am adding my client side and server side code below.
useChat hook in react client to receive a server message
const useChat = (roomId) => {
const [messages, setMessages] = useState([]); // Sent and received messages
const socketRef = useRef();
useEffect(() => {
// Creates a WebSocket connection
socketRef.current = io(SOCKET_SERVER_URL, {
query: { roomId }, transports: ['websocket'] });
// Listens for incoming messages
socketRef.current.on('msgToClient', (message) => {
const incomingMessage = {
...message,
ownedByCurrentUser: message.senderId === socketRef.current.id,
};
setMessages((messages) => [...messages, incomingMessage]);
});
// Destroys the socket reference
// when the connection is closed
return () => {
socketRef.current.disconnect();
};
}, [roomId]);
return { messages, sendMessage, joinRoom };
};
export default useChat;
message.gateway in NestJs to send it to client
@WebSocketGateway()
export class MessageGateway
implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
@WebSocketServer() socket: Socket;
private logger: Logger = new Logger('MessageGateway');
@SubscribeMessage('msgToServer')
public handleMessage(client: Socket, payload: any): void {
this.socket.to(client.handshake.query.roomId).emit('msgToClient', payload);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论