Screen.js 7.23 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
  const [socket, setSocket] = useState(null);
  const [users, setUsers] = useState([]);
  const { roomId, channelId } = useParams();
Kim, Chaerin's avatar
시연2    
Kim, Chaerin committed
12
  const url = `${roomId}/${channelId}`;
Kim, Chaerin's avatar
Kim, Chaerin committed
13
14
15
16

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

Kim, Chaerin's avatar
Kim, Chaerin committed
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  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
34
  useEffect(() => {
Kim, Chaerin's avatar
Kim, Chaerin committed
35
    let newSocket = io.connect("http://localhost:8080");
Kim, Chaerin's avatar
Kim, Chaerin committed
36
    let localStream;
Kim, Chaerin's avatar
Kim, Chaerin committed
37
38
    // console.log("newSocket", newSocket.id);
    //
Kim, Chaerin's avatar
Kim, Chaerin committed
39
    newSocket.on("userEnter", (data) => {
Kim, Chaerin's avatar
Kim, Chaerin committed
40
      console.log(data);
Kim, Chaerin's avatar
Kim, Chaerin committed
41
42
43
44
45
46
47
      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);
48
49
50
      }
    });

Kim, Chaerin's avatar
Kim, Chaerin committed
51
52
53
54
    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
55
56
    });

Kim, Chaerin's avatar
Kim, Chaerin committed
57
58
59
    newSocket.on("getSenderAnswer", async (data) => {
      try {
        console.log("get sender answer");
Kim, Chaerin's avatar
Kim, Chaerin committed
60
        console.log(data.sdp);
Kim, Chaerin's avatar
Kim, Chaerin committed
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
90
        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
91
        console.log(data);
Kim, Chaerin's avatar
Kim, Chaerin committed
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
        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,
Kim, Chaerin's avatar
시연2    
Kim, Chaerin committed
122
          roomID: url,
Kim, Chaerin's avatar
Kim, Chaerin committed
123
124
125
126
127
        });
      })
      .catch((error) => {
        console.log(`getUserMedia error: ${error}`);
      });
128
  }, []);
seoyeon's avatar
seoyeon committed
129

Kim, Chaerin's avatar
Kim, Chaerin committed
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
  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,
Kim, Chaerin's avatar
시연2    
Kim, Chaerin committed
152
        roomID: url,
Kim, Chaerin's avatar
Kim, Chaerin committed
153
154
155
156
157
158
159
160
161
162
163
164
165
166
      });
    } 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
167
      console.log(sdp, newSocket.id, senderSocketID, roomId);
Kim, Chaerin's avatar
Kim, Chaerin committed
168
169
170
171
      newSocket.emit("receiverOffer", {
        sdp,
        receiverSocketID: newSocket.id,
        senderSocketID,
Kim, Chaerin's avatar
시연2    
Kim, Chaerin committed
172
        roomID: url,
Kim, Chaerin's avatar
Kim, Chaerin committed
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
245
      });
    } 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
246
247
  return (
    <div className="container">
Kim, Chaerin's avatar
Kim, Chaerin committed
248
249
250
251
252
      <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
253
          <img
Kim, Chaerin's avatar
Kim, Chaerin committed
254
            className="rounded-circle me-2"
seoyeon's avatar
seoyeon committed
255
256
257
258
            src="/cherry.jpg"
            width="40px"
            height="40px"
          />
Kim, Chaerin's avatar
Kim, Chaerin committed
259
          {user}님이 화면공유중...
Kim, Chaerin's avatar
Kim, Chaerin committed
260
        </div>
Kim, Chaerin's avatar
Kim, Chaerin committed
261
262
263
264
265
266
267
268
269
270
271
272
        <video
          style={{
            display: "flex",
            justifyContent: "center",
            width: 375,
            height: 260,
            backgroundColor: "black",
          }}
          muted
          ref={localVideoRef}
          autoPlay
        />
Kim, Chaerin's avatar
시연    
Kim, Chaerin committed
273
274
275
        {users.map((user, index) => {
          return <Video key={index} stream={user.stream} />;
        })}
Kim, Chaerin's avatar
Kim, Chaerin committed
276
277
      </div>
    </div>
Kim, Chaerin's avatar
Kim, Chaerin committed
278
279
  );
};
Kim, Chaerin's avatar
Kim, Chaerin committed
280

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