| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" />
- <meta http-equiv="X-UA-Compatible" content="IE=edge" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>car</title>
- <script src="./socket.io.min.js"></script>
- <style>
- video {
- width: 500px;
- height: 400px;
- background: none;
- object-fit: fill;
- border: solid 1px red;
- }
- </style>
- </head>
- <body>
- <div>
- <video id="v2" autoplay playsinline muted></video>
- </div>
- <!-- webrtc -->
- <script>
- let RTC = null
- const socket = io({
- auth: {
- roomID: "feiCar",
- name: "ctrl",
- },
- transports: ["websocket"],
- });
- socket.on("connect", async () => {
- RTC = new RTCPeerConnection({
- bundlePolicy: "max-bundle"
- });
- // listen state
- RTC.onicegatheringstatechange = () => {
- console.log("GatheringState: ", RTC.iceGatheringState);
- if (RTC.iceGatheringState === "complete") {
- const answer = RTC.localDescription;
- socket.emit("msg", answer);
- }
- };
- // listen track
- RTC.ontrack = (evt) => {
- console.log("track", evt.streams[0]);
- const video = document.getElementById("v2");
- video.srcObject = evt.streams[0];
- };
- console.log("连接成功监听webrtc");
- });
- // 发送anwser
- socket.on("msg", async (data) => {
- console.log("用户信息", data);
- if (data.type == "offer") {
- await this.Peer.setRemoteDescription(data);
- const answer = await this.Peer.createAnswer();
- await this.Peer.setLocalDescription(answer);
- }
- });
- // 监听加入
- socket.on('joined', user => {
- console.log(`${user.name}加入${user.roomID}房间`)
- // 向其它用户发送开始webrtc
- socket.emit('msg', { type: 'startRTC' })
- })
- // 监听离开
- socket.on('leaved', user => {
- console.log(`${user.name}离开${user.roomID}房间`)
- RTC.close()
- })
- // 断开连接
- socket.on("connect_error", (err) => {
- console.log("连接错误", err);
- if (RTC) RTC.close()
- });
- </script>
- </body>
- </html>
|