[javascript] Socket.io를 사용하여 실시간 애니메이션을 어떻게 구현할 수 있나요?

Socket.io는 웹 응용 프로그램에서 실시간 통신을 구현하는 데 사용되는 JavaScript 라이브러리입니다. 이를 활용하여 실시간 애니메이션을 구현하는 방법을 알아보겠습니다.

  1. Socket.io 설치하기
    npm install socket.io
    

    위 명령을 사용하여 Socket.io를 프로젝트에 설치합니다.

  2. 서버 측 설정하기
    const express = require("express");
    const app = express();
    const http = require("http").createServer(app);
    const io = require("socket.io")(http);
    
    app.use(express.static("public")); // 정적 파일 제공
    app.get("/", (req, res) => {
      res.sendFile(__dirname + "/index.html"); // 클라이언트 페이지 제공
    });
    
    io.on("connection", (socket) => {
      console.log("새로운 클라이언트가 연결되었습니다.");
    
      // 클라이언트로부터 좌표 정보를 받아 애니메이션 실행
      socket.on("animation", (data) => {
        // 좌표 정보를 다른 클라이언트들에게 전달
        socket.broadcast.emit("animation", data);
      });
    
      // 클라이언트와의 연결이 끊어졌을 때
      socket.on("disconnect", () => {
        console.log("클라이언트와의 연결이 종료되었습니다.");
      });
    });
    
    http.listen(3000, () => {
      console.log("서버가 시작되었습니다.");
    });
    

    위 코드는 Socket.io를 사용하여 서버를 설정하는 예시입니다. 서버는 3000번 포트에서 실행됩니다.

  3. 클라이언트 측 설정하기
    <!DOCTYPE html>
    <html>
    
    <head>
      <title>실시간 애니메이션</title>
      <style>
        #animation-div {
          width: 200px;
          height: 200px;
          background-color: red;
          position: absolute;
          top: 0;
          left: 0;
          transition: top 1s, left 1s;
        }
      </style>
    </head>
    
    <body>
      <div id="animation-div"></div>
    
      <script src="/socket.io/socket.io.js"></script>
      <script>
        const socket = io();
    
        const animationDiv = document.getElementById("animation-div");
    
        // 좌표 정보를 서버로 전송
        document.addEventListener("mousemove", (event) => {
          const x = event.clientX;
          const y = event.clientY;
          socket.emit("animation", { x, y });
        });
    
        // 좌표 정보를 받아 애니메이션 실행
        socket.on("animation", (data) => {
          animationDiv.style.top = `${data.y}px`;
          animationDiv.style.left = `${data.x}px`;
        });
      </script>
    </body>
    
    </html>
    

    위 코드는 클라이언트 측에서 Socket.io를 사용하여 실시간 애니메이션을 구현하는 예시입니다. 마우스의 좌표 정보를 서버로 전송하고, 서버로부터 받은 좌표 정보를 기반으로 애니메이션을 실행합니다.

Socket.io를 통해 실시간 애니메이션을 구현할 수 있습니다. 서버와 클라이언트 간의 실시간 통신을 통해 데이터를 전송하고, 받은 데이터를 바탕으로 애니메이션을 제어할 수 있습니다.

참고 링크: