Screen.js 7.09 KB
Newer Older
Kim, Chaerin's avatar
Kim, Chaerin committed
1
2
3
4
5
6
7
import React, { useState } from "react";
import io from "socket.io-client";
import { useRef } from "react";
import { useEffect } from "react";
import Video from "./Video";
import { useParams } from "react-router-dom";

Kim, Chaerin's avatar
Kim, Chaerin committed
8
const Screen = () => {
Kim, Chaerin's avatar
Kim, Chaerin committed
9
10
11
12
13
14
15
  const [socket, setSocket] = useState(null);
  const [users, setUsers] = useState([]);
  const { roomId, channelId } = useParams();

  const user = "00";
  let localVideoRef = useRef(null);

Kim, Chaerin's avatar
Kim, Chaerin committed
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  let sendPC;
  let receivePCs;

  // 방화벽 등의 보호장치를 거쳐 ip로 연결하기 위한 설정
  const pc_config = {
    iceServers: [
      // {
      //   urls: 'stun:[STUN_IP]:[PORT]',
      //   'credentials': '[YOR CREDENTIALS]',
      //   'username': '[USERNAME]'
      // },
      {
        urls: "stun:stun.l.google.com:19302",
      },
    ],
  };

Kim, Chaerin's avatar
Kim, Chaerin committed
33
  useEffect(() => {
Kim, Chaerin's avatar
Kim, Chaerin committed
34
    let newSocket = io.connect("http://localhost:8080");
Kim, Chaerin's avatar
Kim, Chaerin committed
35
    let localStream;
Kim, Chaerin's avatar
Kim, Chaerin committed
36
37
    // console.log("newSocket", newSocket.id);
    //
Kim, Chaerin's avatar
Kim, Chaerin committed
38
    newSocket.on("userEnter", (data) => {
Kim, Chaerin's avatar
Kim, Chaerin committed
39
      console.log(data);
Kim, Chaerin's avatar
Kim, Chaerin committed
40
41
42
43
44
45
46
      createReceivePC(data.id, newSocket);
    });

    newSocket.on("allUsers", (data) => {
      let len = data.users.length;
      for (let i = 0; i < len; i++) {
        createReceivePC(data.users[i].id, newSocket);
47
48
49
      }
    });

Kim, Chaerin's avatar
Kim, Chaerin committed
50
51
52
53
    newSocket.on("userExit", (data) => {
      receivePCs[data.id].close();
      delete receivePCs[data.id];
      setUsers((users) => users.filter((user) => user.id !== data.id));
Kim, Chaerin's avatar
Kim, Chaerin committed
54
55
    });

Kim, Chaerin's avatar
Kim, Chaerin committed
56
57
58
    newSocket.on("getSenderAnswer", async (data) => {
      try {
        console.log("get sender answer");
Kim, Chaerin's avatar
Kim, Chaerin committed
59
        console.log(data.sdp);
Kim, Chaerin's avatar
Kim, Chaerin committed
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
        await sendPC.setRemoteDescription(new RTCSessionDescription(data.sdp));
      } catch (error) {
        console.log(error);
      }
    });

    newSocket.on("getSenderCandidate", async (data) => {
      try {
        console.log("get sender candidate");
        if (!data.candidate) return;
        sendPC.addIceCandidate(new RTCIceCandidate(data.candidate));
        console.log("candidate add success");
      } catch (error) {
        console.log(error);
      }
    });

    newSocket.on("getReceiverAnswer", async (data) => {
      try {
        console.log(`get socketID(${data.id})'s answer`);
        let pc = receivePCs[data.id];
        await pc.setRemoteDescription(data.sdp);
        console.log(`socketID(${data.id})'s set remote sdp success`);
      } catch (error) {
        console.log(error);
      }
    });

    newSocket.on("getReceiverCandidate", async (data) => {
      try {
Kim, Chaerin's avatar
Kim, Chaerin committed
90
        console.log(data);
Kim, Chaerin's avatar
Kim, Chaerin committed
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
        console.log(`get socketID(${data.id})'s candidate`);
        let pc = receivePCs[data.id];
        if (!data.candidate) return;
        pc.addIceCandidate(new RTCIceCandidate(data.candidate));
        console.log(`socketID(${data.id})'s candidate add success`);
      } catch (error) {
        console.log(error);
      }
    });

    setSocket(newSocket);

    navigator.mediaDevices
      .getUserMedia({
        audio: true,
        video: {
          width: 375,
          height: 260,
        },
      })
      .then((stream) => {
        if (localVideoRef.current) localVideoRef.current.srcObject = stream;

        localStream = stream;

        sendPC = createSenderPeerConnection(newSocket, localStream);
        createSenderOffer(newSocket);

        newSocket.emit("joinRoom", {
          id: newSocket.id,
          roomID: roomId,
        });
      })
      .catch((error) => {
        console.log(`getUserMedia error: ${error}`);
      });
127
  }, []);
seoyeon's avatar
seoyeon committed
128

Kim, Chaerin's avatar
Kim, Chaerin committed
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
  const createReceivePC = (id, newSocket) => {
    try {
      console.log(`socketID(${id}) user entered`);
      let pc = createReceiverPeerConnection(id, newSocket);
      createReceiverOffer(pc, newSocket, id);
    } catch (error) {
      console.log(error);
    }
  };

  const createSenderOffer = async (newSocket) => {
    try {
      let sdp = await sendPC.createOffer({
        offerToReceiveAudio: false,
        offerToReceiveVideo: false,
      });
      console.log("create sender offer success");
      await sendPC.setLocalDescription(new RTCSessionDescription(sdp));

      newSocket.emit("senderOffer", {
        sdp,
        senderSocketID: newSocket.id,
        roomID: roomId,
      });
    } catch (error) {
      console.log(error);
    }
  };

  const createReceiverOffer = async (pc, newSocket, senderSocketID) => {
    try {
      let sdp = await pc.createOffer({
        offerToReceiveAudio: true,
        offerToReceiveVideo: true,
      });
      console.log("create receiver offer success");
      await pc.setLocalDescription(new RTCSessionDescription(sdp));
Kim, Chaerin's avatar
Kim, Chaerin committed
166
      console.log(sdp, newSocket.id, senderSocketID, roomId);
Kim, Chaerin's avatar
Kim, Chaerin committed
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
      newSocket.emit("receiverOffer", {
        sdp,
        receiverSocketID: newSocket.id,
        senderSocketID,
        roomID: roomId,
      });
    } catch (error) {
      console.log(error);
    }
  };

  const createSenderPeerConnection = (newSocket, localStream) => {
    let pc = new RTCPeerConnection(pc_config);

    pc.onicecandidate = (e) => {
      if (e.candidate) {
        console.log("sender PC onicecandidate");
        newSocket.emit("senderCandidate", {
          candidate: e.candidate,
          senderSocketID: newSocket.id,
        });
      }
    };

    pc.oniceconnectionstatechange = (e) => {
      console.log(e);
    };

    if (localStream) {
      console.log("localstream add");
      localStream.getTracks().forEach((track) => {
        pc.addTrack(track, localStream);
      });
    } else {
      console.log("no local stream");
    }

    // return pc
    return pc;
  };

  const createReceiverPeerConnection = (socketID, newSocket) => {
    let pc = new RTCPeerConnection(pc_config);

    // add pc to peerConnections object
    receivePCs = { ...receivePCs, [socketID]: pc };

    pc.onicecandidate = (e) => {
      if (e.candidate) {
        console.log("receiver PC onicecandidate");
        newSocket.emit("receiverCandidate", {
          candidate: e.candidate,
          receiverSocketID: newSocket.id,
          senderSocketID: socketID,
        });
      }
    };

    pc.oniceconnectionstatechange = (e) => {
      console.log(e);
    };

    pc.ontrack = (e) => {
      console.log("ontrack success");
      setUsers((oldUsers) => oldUsers.filter((user) => user.id !== socketID));
      setUsers((oldUsers) => [
        ...oldUsers,
        {
          id: socketID,
          stream: e.streams[0],
        },
      ]);
    };

    // return pc
    return pc;
  };

Kim, Chaerin's avatar
Kim, Chaerin committed
245
246
  return (
    <div className="container">
Kim, Chaerin's avatar
Kim, Chaerin committed
247
248
249
250
251
      <div className="mt-3" style={{ backgroundColor: "#FCF4FF" }}>
        <div
          className="m-2 d-flex fw-bold text-center"
          style={{ color: "#4A4251", fontSize: "20px" }}
        >
seoyeon's avatar
seoyeon committed
252
          <img
Kim, Chaerin's avatar
Kim, Chaerin committed
253
            className="rounded-circle me-2"
seoyeon's avatar
seoyeon committed
254
255
256
257
            src="/cherry.jpg"
            width="40px"
            height="40px"
          />
Kim, Chaerin's avatar
Kim, Chaerin committed
258
          {user}님이 화면공유중...
Kim, Chaerin's avatar
Kim, Chaerin committed
259
        </div>
Kim, Chaerin's avatar
Kim, Chaerin committed
260
261
262
263
264
265
266
267
268
269
270
271
        <video
          style={{
            display: "flex",
            justifyContent: "center",
            width: 375,
            height: 260,
            backgroundColor: "black",
          }}
          muted
          ref={localVideoRef}
          autoPlay
        />
Kim, Chaerin's avatar
Kim, Chaerin committed
272
273
      </div>
    </div>
Kim, Chaerin's avatar
Kim, Chaerin committed
274
275
  );
};
Kim, Chaerin's avatar
Kim, Chaerin committed
276

Kim, Chaerin's avatar
Kim, Chaerin committed
277
export default Screen;