본문 바로가기
개발/React

리액트, Node JS - Socket.IO namespace로 채팅방 관리하기 (Managing Chat Room using namespace)

by 피로물든딸기 2024. 4. 1.
반응형

리액트 전체 링크

Node JS 전체 링크

 

참고

chat-ui-kit-react로 채팅창 UI 만들기
로그인 + 채팅방 UI 만들기
채팅방 변경하기
채팅방 들어오고 나갈 때 표시하기
Socket.IO로 채팅하기
Socket.IO Room으로 채팅방 관리하기
Socket.IO namespace로 채팅방 관리하기
Socket.IO로 중복 로그인 제한하기

- Socket.IO Middleware로 중복 로그인 방지하기

 

room 대신 namespace를 이용해서 채팅방을 구현해 보자.


namespace

 

Socket.IOnamespace를 이용해서 소켓 그룹을 만들어 분리된 통신 채널을 사용할 수 있다.

express라우터와 비슷한 개념이다.

 

예를 들어 아래와 같이 room0에 대한 namespace를 만들 수 있다.

namespace로 방을 구분하기 때문에 이전 글에서 사용한 room은 삭제하였다.

const room0 = (io) => {
    const namespace = io.of("/room0");
  
    namespace.on("connection", (socket) => {
      console.log("Client connected to room0");
  
      socket.on("sendMessage", (message) => {
        socket.broadcast.emit("respondMessage", message);
      });
  
      socket.on("disconnect", () => {
        console.log("User disconnected from room0");
      });
    });
  };
  
  module.exports = room0;

 

클라이언트에서는 서버IP /room0만 추가해서 통신을 할 수 있다.

let socketIORoom0 = io("http://localhost:3333/room0");

 

socketIOServer.js는 다음과 같이 room0, 1을 모듈화 할 수 있다.

const { Server } = require("socket.io");

const io = new Server("3333", {
  cors: {
    origin: "http://localhost:3000",
  },
});

const room0 = require('./room0');
const room1 = require('./room1');

room0(io);
room1(io);

클라이언트 구현

 

채팅방이 2개만 있다고 가정한다.

따라서 클라이언트에는 socket이 2개 필요하다. (namespace로 구분)

let socketIORoom0 = io("http://localhost:3333/room0", { autoConnect: false });
let socketIORoom1 = io("http://localhost:3333/room1", { autoConnect: false });

 

namespace를 관리하기 위해 useStatesocket을 만든다. (최초 진입시 0번 방 입장)

const ChatUI = () => {
  ...
  const [socketIO, setSocketIO] = useState(socketIORoom0);

 

sendMessage에서 이전 글에 있던 roomID를 서버에 보내는 코드는 모두 원복되었다. (전체 코드 참고)

  const init = () => {
    socketIO.connect();
    
    ...
    
    socketIO.emit("sendMessage", enterSeparator);
  };

 

changeRoom 이벤트에 의해 namespace가 변경된다.

따라서 changeRoom에서 현재 namespace 통신을 해제하고, 새로운 namespace로 연결한다.

  const changeRoom = (index) => {
    if(activeID === index) return;
    
    ...

    let tempSocket = socketIO;

    tempSocket.emit("sendMessage", leftSeparator);
    tempSocket.disconnect();
    tempSocket = index === 0 ? socketIORoom0 : socketIORoom1;
    tempSocket.connect();
    tempSocket.emit("sendMessage", enterSeparator);

    setSocketIO(tempSocket);

    setMessages(temp);
    setActiveID(index);
  }

 

위에서 setSocketIO가 변경될 때, socketIOcallback이 초기화되도록 useEffect에 변수를 추가한다.

  useEffect(() => {
    if (!socketIO) return;

    socketIO.on("respondMessage", respondMessageCallback);
    return () => {
      socketIO.off("respondMessage", respondMessageCallback);      
    };
  }, [socketIO]);

전체 코드는 다음과 같다.

 

socketIOServer.js

const { Server } = require("socket.io");

const io = new Server("3333", {
  cors: {
    origin: "http://localhost:3000",
  },
});

const room0 = require('./room0');
const room1 = require('./room1');

room0(io);
room1(io);

 

room0.js

const room0 = (io) => {
    const namespace = io.of("/room0");
  
    namespace.on("connection", (socket) => {
      console.log("Client connected to room0");
  
      socket.on("sendMessage", (message) => {
        socket.broadcast.emit("respondMessage", message);
      });
  
      socket.on("disconnect", () => {
        console.log("User disconnected from room0");
      });
    });
  };
  
  module.exports = room0;

 

room1.js

const room1 = (io) => {
    const namespace = io.of("/room1");
  
    namespace.on("connection", (socket) => {
      console.log("Client connected to room1");
  
      socket.on("sendMessage", (message) => {
        socket.broadcast.emit("respondMessage", message);
      });
  
      socket.on("disconnect", () => {
        console.log("User disconnected from room1");
      });
    });
  };
  
  module.exports = room1;

 

ChatUI.js (Client)

import React, { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";
import { io } from "socket.io-client";

import styles from "@chatscope/chat-ui-kit-styles/dist/default/styles.min.css";

import {
  MainContainer,
  ChatContainer,
  MessageList,
  Message,
  MessageInput,
  Avatar,
  Sidebar,
  ConversationList,
  Conversation,
  ConversationHeader,
  VoiceCallButton,
  VideoCallButton,
  InfoButton,
  MessageSeparator,
} from "@chatscope/chat-ui-kit-react";

let socketIORoom0 = io("http://localhost:3333/room0", { autoConnect: false });
let socketIORoom1 = io("http://localhost:3333/room1", { autoConnect: false });

const AVATAR_IMAGE =
  "https://img1.daumcdn.net/thumb/C428x428/?scode=mtistory2&fname=https%3A%2F%2Ftistory3.daumcdn.net%2Ftistory%2F4431109%2Fattach%2F3af65be1d8b64ece859b8f6d07fafadc";

const AVATAR_MAP = {
  Lilly: "https://chatscope.io/storybook/react/assets/lilly-aj6lnGPk.svg",
  Joe: "https://chatscope.io/storybook/react/assets/joe-v8Vy3KOS.svg",
  Emily: "https://chatscope.io/storybook/react/assets/emily-xzL8sDL2.svg",
  Akane: "https://chatscope.io/storybook/react/assets/akane-MXhWvx63.svg",
  Eliot: "https://chatscope.io/storybook/react/assets/eliot-JNkqSAth.svg",
  Zoe: "https://chatscope.io/storybook/react/assets/zoe-E7ZdmXF0.svg",
};

const defaultMessage = [];
const defaultMessagePatrik = [];
const totalMessages = [defaultMessage, defaultMessagePatrik];

const defaultConversation = [
  {
    info: "",
    lastSenderName: "bloodstrawberry",
    name: "bloodstrawberry",
    src: AVATAR_IMAGE,
    status: "available",
  },
  {
    info: "",
    lastSenderName: "Patrik",
    name: "Patrik",
    src: "https://chatscope.io/storybook/react/assets/patrik-yC7svbAR.svg",
    status: "invisible",
  },
];

const ChatUI = () => {
  const location = useLocation();
  const [loginID, setLoginID] = useState("");

  const [activeID, setActiveID] = useState(0);
  const [messages, setMessages] = useState(totalMessages);
  const [socketIO, setSocketIO] = useState(socketIORoom0);

  const getMessageComponent = (totalMessages) => {
    let data = totalMessages[activeID];

    return data.map((item, index) => {
      if(item.type !== "separator") {
        item.model.direction = item.avatar.name === loginID ? "outgoing" : "incoming";
      }
  
      return item.type === "separator" ? (
        <MessageSeparator key={index} content={item.content} />
      ) : (
        <Message key={index} model={item.model}>
          {item.avatar && item.model.direction === "incoming" ? (
            <Avatar src={item.avatar.src} name={item.avatar.name} />
          ) : null}
        </Message>
      );
    });
  };

  const changeRoom = (index) => {
    if(activeID === index) return;
    
    let leftSeparator = {
      type : "separator",
      content : `${loginID} has left the chatroom.`,
    }

    let enterSeparator = {
      type : "separator",
      content : `${loginID} has entered the chatroom.`,
    }

    let temp = [...totalMessages];
    temp[activeID].push(leftSeparator);
    temp[index].push(enterSeparator);

    let tempSocket = socketIO;

    tempSocket.emit("sendMessage", leftSeparator);
    tempSocket.disconnect();
    tempSocket = index === 0 ? socketIORoom0 : socketIORoom1;
    tempSocket.connect();
    tempSocket.emit("sendMessage", enterSeparator);

    setSocketIO(tempSocket);

    setMessages(temp);
    setActiveID(index);
  }

  const getConversationComponent = (data) => {
    return data.map((item, index) => {
      return (
        <Conversation
          key={index}
          active={index === activeID}
          info={item.info}
          lastSenderName={item.lastSenderName}
          name={item.name}
          onClick={() => changeRoom(index)}
        >
          <Avatar name={item.name} src={item.src} status={item.status} />
        </Conversation>
      );
    });
  };

  const handleSend = (input) => {
    let newMessage = {
      model: {
        message: input,
        // direction: "outgoing",
      },
      avatar: {
        src: AVATAR_MAP[loginID],
        name: loginID,
      },
    };

    let temp = [...totalMessages];
    temp[activeID].push(newMessage);
    setMessages(temp);

    socketIO.emit("sendMessage", newMessage);
  };

  const init = () => {
    socketIO.connect();
    
    setLoginID(location.state.loginID);

    let enterSeparator = {
      type : "separator",
      content : `${location.state.loginID} has entered the chatroom.`,
    }

    let temp = [...totalMessages];
    temp[activeID].push(enterSeparator);

    setMessages(temp);    
    socketIO.emit("enter", activeID);
    socketIO.emit("sendMessage", enterSeparator);
  };

  const respondMessageCallback = (message) => {
    let temp = [...totalMessages];
    temp[activeID].push(message);
    setMessages(temp);  
  }

  useEffect(() => {
    if (!socketIO) return;

    socketIO.on("respondMessage", respondMessageCallback);
    return () => {
      socketIO.off("respondMessage", respondMessageCallback);      
    };
  }, [socketIO]);

  useEffect(init, []);

  return (
    <div>
      <Conversation
        info="I'm fine, thank you, and you?"
        lastSenderName={loginID}
        name={loginID}
      >
        <Avatar name={loginID} src={AVATAR_MAP[loginID]} status="available" />
      </Conversation>
      <MessageSeparator style={{ marginTop: 5, marginBottom: 5 }} />
      <MainContainer
        responsive
        style={{
          height: "300px",
        }}
      >
        <Sidebar position="left">
          <ConversationList>
            {getConversationComponent(defaultConversation)}
          </ConversationList>
        </Sidebar>
        <ChatContainer>
          <ConversationHeader>
            <ConversationHeader.Back />
            <Avatar
              name={defaultConversation[activeID].name}
              src={defaultConversation[activeID].src}
            />
            {activeID === 0 ? (
              <ConversationHeader.Content
                info="Active 10 mins ago"
                userName="bloodstrawberry"
              />
            ) : (
              <ConversationHeader.Content
                info="Active 7 hours ago"
                userName="Patrik"
              />
            )}
            <ConversationHeader.Actions>
              <VoiceCallButton />
              <VideoCallButton />
              <InfoButton />
            </ConversationHeader.Actions>
          </ConversationHeader>
          <MessageList>
            {getMessageComponent(messages)}
          </MessageList>

          <MessageInput placeholder="Type message here" onSend={handleSend} />
        </ChatContainer>
      </MainContainer>
    </div>
  );
};

export default ChatUI;
반응형

댓글