[유데미x스나이퍼팩토리] 10주 완성 프로젝트 캠프 12일차 - WebSocket

강경서·2023년 7월 1일
0
post-thumbnail

🛸 HTTP vs WebSocket


HTTP

HTTP는 서버와 클라이언트 사이의 요청과 응답 뒤에 서버는 클라이언트의 정보를 저장하지 않는 Staeless 프로토콜입니다.


WebSocket

WebSocket은 서버와 클라이언트 사이에 소켓 커넥션을 유지하면서 양방향 통신이 가능한 프로토콜입니다.


🧭 Socket.io

Socket.IO는 실시간 웹 애플리케이션을 위한 이벤트 기반 라이브러리로, 웹 클라이언트와 서버 간의 실시간 양방향 통신인 WebSocket 프로토콜을 가능케 합니다.


Express Server

  • server.js
const express = require("express");
const http = require("http");
const socketIO = require("socket.io");
const cors = require("cors");

const app = express();
app.use(cors());
const server = http.createServer(app);
const io = socketIO(server, {
  cors: {
    origin: "http://localhost:3000",  
    methods: ["GET", "POST"],  
  },
});

io.on("connection", (socket) => {
  console.log("새로운 클라이언트가 연결되었습니다.");
 
  socket.on("message", (message) => {
    console.log("새로운 메시지:", message);
    io.emit("message", message);
  });

  // 클라이언트 연결 해제 처리
  socket.on("disconnect", () => {
    console.log("클라이언트가 연결을 해제하였습니다.");
  });
});

server.listen(3001, () => {
  console.log("서버가 3001 포트에서 실행 중입니다.");
});

Express 프레임워크와 Socket.io 라이브러리를 이용하여 WebSocket 서버를 만들었습니다.
WebSocket 서버는 on 메서드를 통해 클라이언트의 접속인 "connection"을 받습니다. 클라이언트와 연결시 socket 객체를 받으며, socket 객체는 on 메소드를 통해 데이터를 받습니다. emit 메서드는 클라이언트에게 데이터를 전달 할 수 있습니다.

Express : Node.js를 위한 빠르고 개방적인 간결한 웹 프레임워크입니다.

--

Chat

  • src/chat.js
import React, { useState, useEffect } from "react";
import { io } from "socket.io-client";

const socket = io("http://localhost:3001");

function Chat() {
  const [username, setUsername] = useState("");
  const [messages, setMessages] = useState([]);
  const [inputValue, setInputValue] = useState("");

  useEffect(() => {
    socket.on("message", handleMessage);
    return () => {
      socket.off("message", handleMessage);
    };
  }, []);

  const handleMessage = (message) => {
    setMessages((pre) => [...pre, message]);
  };

  const handleMessageSubmit = () => {
    if (inputValue.trim() !== "") {
      const currentTime = new Date().toLocaleDateString();
      socket.emit("message", {
        username,
        content: inputValue,
        time: currentTime,
      });
      setInputValue("");
    }
  };

  return (
    <div>
      <input
        type="text"
        value={username}
        onChange={(event) => setUsername(event.target.value)}
        placeholder="사용자 이름을 입력하세요."
      />
      <h1>채팅</h1>
      <div>
        {messages.map((message, index) => (
          <p key={index}>
            {message.username} : {message.content} - {message.time}
          </p>
        ))}
      </div>
      <input
        type="text"
        value={inputValue}
        onChange={(event) => setInputValue(event.target.value)}
      />
      <button onClick={handleMessageSubmit}>전송</button>
    </div>
  );
}

export default Chat;

채팅 컴포넌트는 useEffect를 통해 Websocket 서버의 이벤트를 받습니다.클라이어트 내에서도 on 메서드와 emit 메서드를 이용하여 서버와 데이터를 주고 받을 수 있습니다,

--

📝 후기

WebSocket을 통해 실시간 채팅 기능을 구현할 수 있었습니다. HTTP 프로토콜의 Staeless한 특징 때문에 구현하기 힘든 실시간 데이터 소통을 Socket.io 라이브러리를 통해 만든 채팅 기능을 통해 WebSocket 프로토콜의 원리를 이해할 수 있었습니다. 채팅뿐만 아니라 실시간 데이터 소통이 필요한 기능이 있는 웹을 제작하게 된다면 꼭 적용하고 싶은 프로토콜이었습니다.


🧾 Reference



본 후기는 유데미-스나이퍼팩토리 10주 완성 프로젝트캠프 학습 일지 후기로 작성 되었습니다.

#프로젝트캠프 #프로젝트캠프후기 #유데미 #스나이퍼팩토리 #웅진씽크빅 #인사이드아웃 #IT개발캠프 #개발자부트캠프 #리액트 #react #부트캠프 #리액트캠프

profile
기록하고 배우고 시도하고

0개의 댓글