본문 바로가기

Spring Boot

[Node.js] WebRTC 멀티화상채팅 기본 데모소스

반응형
const SimplePeer = require("simple-peer");
const express = require("express");
const http = require("http");
const socketio = require("socket.io");

// Initialize Express and HTTP server
const app = express();
const server = http.createServer(app);
const io = socketio(server);

// Serve static files from the "public" directory
app.use(express.static("public"));

// Keep track of connected clients
const clients = [];

// Handle new WebSocket connections from clients
io.on("connection", socket => {
  // Initialize SimplePeer for the new client
  const peer = new SimplePeer({
    initiator: socket.request._query.initiator === "true",
    stream: socket.request._query.stream === "true",
    trickle: false
  });

  // Add the new client to the list of connected clients
  clients.push(peer);

  // Send signaling data between clients
  peer.on("signal", data => {
    socket.emit("signal", data);
  });

  // Handle received chat messages
  socket.on("message", data => {
    peer.send(data);
  });

  // Handle incoming stream data
  peer.on("stream", stream => {
    // Add the incoming stream to the peer's data object
    peer.stream = stream;

    // Emit the new stream data to all connected clients
    io.emit("stream", {
      id: peer.id,
      stream: stream
    });
  });

  // Handle peer disconnections
  peer.on("close", () => {
    // Remove the peer from the list of connected clients
    clients.splice(clients.indexOf(peer), 1);

    // Emit the peer disconnection event to all connected clients
    io.emit("disconnected", {
      id: peer.id
    });
  });
});

// Start the HTTP server
server.listen(3000, () => {
  console.log("Server started on http://localhost:3000");
});

단순 피어 라이브러리를 사용하여 WebRTC 피어 연결을 처리하고 socket.io을 사용하여 클라이언트 간의 실시간 통신을 처리합니다. 새 클라이언트가 연결되면 해당 클라이언트에 대해 새 SimplePeer 인스턴스가 생성됩니다. 신호 이벤트는 피어 연결을 설정하기 위해 클라이언트 간에 신호 데이터를 전송하는 데 사용됩니다. 채팅 메시지는 메시지 이벤트를 사용하여 전송되고 수신 스트림 데이터는 스트림 이벤트를 사용하여 연결된 모든 클라이언트에 전송됩니다. 클라이언트가 연결을 끊으면 닫기 이벤트가 발생하여 다른 클라이언트에 알립니다.

반응형