[javascript] Socket.io를 사용하여 실시간 편집 가능한 도표를 어떻게 구현할 수 있나요?

Socket.io는 웹 소켓을 지원하는 라이브러리로, 실시간 통신을 구현하는 데 사용됩니다. 이를 활용하여 실시간 편집 가능한 도표를 구현할 수 있습니다. 아래는 이를 위한 간단한 예제 코드입니다:

  1. 서버 측 구현
// server.js

const express = require('express');
const http = require('http');
const socketIO = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketIO(server);

// 클라이언트와 연결되었을 때 실행되는 이벤트 핸들러
io.on('connection', (socket) => {
  console.log('새로운 클라이언트가 연결되었습니다.');

  // 클라이언트가 도형을 그리는 이벤트 핸들러
  socket.on('drawShape', (shape) => {
    // 연결된 모든 클라이언트에게 도형 정보를 전송
    io.emit('drawShape', shape);
  });

  // 클라이언트와의 연결이 끊어졌을 때 실행되는 이벤트 핸들러
  socket.on('disconnect', () => {
    console.log('클라이언트와의 연결이 해제되었습니다.');
  });
});

// 서버를 시작합니다.
server.listen(3000, () => {
  console.log('서버가 시작되었습니다.');
});

  1. 클라이언트 측 구현
<!-- index.html -->

<!DOCTYPE html>
<html>
<head>
  <title>실시간 도표</title>
  <style>
    #canvas {
      border: 1px solid #000;
      height: 400px;
    }
  </style>
</head>
<body>
  <div id="canvas"></div>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.4.1/socket.io.js"></script>
  <script>
    const socket = io();

    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');

    // 도형을 그리는 함수
    function drawShape(shape) {
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      if (shape.type === 'circle') {
        ctx.beginPath();
        ctx.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI);
        ctx.fillStyle = shape.color;
        ctx.fill();
        ctx.closePath();
      }

      if (shape.type === 'rectangle') {
        ctx.beginPath();
        ctx.rect(shape.x, shape.y, shape.width, shape.height);
        ctx.fillStyle = shape.color;
        ctx.fill();
        ctx.closePath();
      }
    }

    // 마우스 클릭 이벤트 핸들러
    canvas.addEventListener('click', (event) => {
      const shape = {
        type: 'circle',
        x: event.offsetX,
        y: event.offsetY,
        radius: 20,
        color: 'blue'
      };

      // 서버에 도형 정보를 전송
      socket.emit('drawShape', shape);
    });

    // 도형 정보를 받았을 때 실행되는 이벤트 핸들러
    socket.on('drawShape', (shape) => {
      drawShape(shape);
    });
  </script>
</body>
</html>

위의 코드를 사용하면 사용자의 클릭 이벤트에 따라 웹 페이지 상에 도형이 그려집니다. 이때, Socket.io를 통해 서버로 도형 정보가 전송되고, 서버는 연결된 모든 클라이언트에게 도형 정보를 다시 전달합니다. 이를 통해 실시간으로 도표를 공유하고 편집할 수 있습니다.

이 예제는 도형 중 원과 사각형만을 다루도록 했지만, 다른 도형을 추가하고 편집 기능을 확장할 수도 있습니다.

참고 문서: