使用 Socket.on 在客户端监听不起作用

发布于 2025-01-10 22:10:33 字数 1559 浏览 0 评论 0原文

当我尝试使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文