카테고리 없음

Til (2023.03.03)

prdg 2023. 3. 5. 14:52

socket.io 친구 개인 채팅2

 

어제 것을 이어서 하면 일단 서로의 소켓 방은 연결이 됐다.

이제 서로 채팅을 보내줘야 하는데 일단 react로 채팅방은 미리 만들어줬다.

그리고 input에 값을 넣어 보낼 때 일어날 함수를 만들어줬다.

보낼 정보를 만들어 준 후 socket에 보내줬다. 보낼 정보엔 방 이름도 넣어서 보내줬다.

  const chatInputOnSubmit = (e: any) => {
    e.preventDefault();
    //빈칸 예외 처리
    if (textInput === "") {
      return;
    }
    //채팅으로 보낼 시간
    const now = new Date();
    const hours = now.getHours();
    const minutes = now.getMinutes();
    const ampm = hours >= 12 ? "오후" : "오전";
    const koreanHours = hours % 12 || 12;
    const timeString = `${ampm} ${koreanHours}:${
      minutes < 10 ? `0${minutes}` : minutes
    }`;
    //채팅으로 보낼 객체
    const newChat = {
      id: myId,
      nickName: myNickName,
      profileImg: ProfileImgUrl,
      text: textInput,
      time: timeString,
      roomId: roomId,
    };

    socket.emit("friendMessage", newChat, { once: true });

    const stringnewChat = JSON.stringify(newChat);
    setChatText((i: any) => [...i, newChat]);
    setTextInput("");
  };

서버에서 받은 후 그 채팅정보를 정보안에 있는 방이름을 이용해 그 방 유저들(친구)에게 보내준다.

  socket.on("friendMessage", (newChat) => {
    console.log(parseInt(newChat.roomId));
    socket
      .to(parseInt(newChat.roomId))
      .emit("friendNew_message", newChat, () => {
      });
  });

그리고 채팅 정보를 react로 받고 useRecoilState를 이용해 배열을 생성해 오는 채팅 하나씩 추가해줬다.

그런데 채팅이 보내는건 한번 보내는데 받을 때 여러번 받아지는 오류가 생겼다.

그래서 useEffect안으로 받는 함수를 넣어줬더니 해결됐다.

  useEffect(() => {
    socket.on("friendNew_message", (newChat) => {
      setChatText((i: any) => [...i, newChat]);
    });
  }, []);